顯示具有 GridView 標籤的文章。 顯示所有文章
顯示具有 GridView 標籤的文章。 顯示所有文章

2014年7月13日 星期日

[RESOLVED] displaying label values in multiline text from gridview


i got 1 gridview which has hyperlink in one column, wen the user clicks the link he will be directed to another page where the details of particular row will be displayed using individual labels. In those labels one of the label must be multilined for me
coz the text will be too long...


Please help me how to get that .


aspx page of label




Hi,


Just go through this post once: http://forums.asp.net/t/1323030.aspx



su88rao






nt useful... any othr solution ?




This problem could be because of absolute sizing or positioning of the label. don't specify the size of label and don't wrap it in absolutely sized container like panel and it will work fine.



i got the solution... by adding style="word-wrap:break-word;" to label and removing the height property of label can achieve tht 




<asp:Label ID="LblDescription" runat="server"
Font-Bold="True" Font-Names="Verdana"
Font-Size="X-Small" ForeColor="#0061C1" Height="16px"
Width="97px" BorderColor="#0061C1"
BorderWidth="1px" style="word-wrap:break-word;" BackColor="White"></asp:Label>

[RESOLVED] How to create time countdown in datalist or gridview


Hi, I'm trying to make public auction list. And I need time countdown for every row in datalist or gridview. How do I create time countdown in datalist or gridview using Asp.Net/C#?




Have a look at this link,


How to display a timer countdown inside my Gridview:

http://forums.asp.net/t/1743407.aspx/1



Thanks sridhar_rs. I solved my problem.


.aspx




























codebehind


protected void Timer1_Tick(object sender, EventArgs e)
{

foreach (GridViewRow item in GridView1.Rows)
{
var label2 = item.FindControl("Label2") as Label;

var label3 = item.FindControl("Label3") as Label;
var time2 = DateTime.Parse(label3.Text);
label.Text = (time2 - DateTime.Now).Days + " Day " + (time2 - DateTime.Now).Hours + " Hours " + (time2 - DateTime.Now).Minutes + " Minutes " + (time2 - DateTime.Now).Seconds + " Seconds";
}

}




[RESOLVED] how to search data from gridview if i have bind it using sqldatasourse


hi


i am new in asp.net


i have a problem to search data from gridview


i have bind gridview using article:http://msdn.microsoft.com/en-us/library/ms972948.aspx


now i want to search record from that


i have textbox to enter search term and serch button to search


note: i want to use like operator to search the records


please help me


thanks in advance





Vjitendra



i have textbox to enter search term and serch button to search


note: i want to use like operator to search the records





Check this link,this is the exact way what you want


http://www.aspdotnet-suresh.com/2011/12/search-records-in-gridview-and.html


[RESOLVED] Gridview adding two Eval to the same Item Template label....


I have an gridview and I need to put the lastname and firstName in the same column, how do I add the firstname and lastname to the same column?



Code:




 

  





'' >



This too will work




[RESOLVED] Make DataCell Content link and open that link in a new window


Hi,


I have already made datagrid cell content link and open that link in a new window, but the problem is that the parent window content disappears and only "[object]" is written on the parent page after click on the link. I want that the Parent page must remains
there and when i click on the link the it opens in a new window as popup.


I have tried the following code


   runat="server"/>


Please correct me if any mistake or tell me some alternate way to do this


Thanks & Regards


Muhammad Arsalan Akhtar



Simply set target="_blank" and use DataNavigateUrlFormatString


    DataNavigateUrlFormatString="LoadBalance.aspx?EmbossLine={0}"
DataTextField="vchrEmbossLine" HeaderText="Emboss Line" Target="_blank" />





your code modify: -



Target="_blank"  runat="server"/>



I have tried this earlier but this will open a new tab, I want to open it as a popup in new window


Thanks for reply ,


plz help me 


Regards 


Muhammad Arsalan Akhtar




Target="_blank"  runat="server"/>


Except hyperlink use anchor tag



adfadfsa


It will work


hyper link only navigate in other tab so best use is that as tag


& you want to use server side you can use make set attribute as
runat="server" id="anchor1"




ars88


if using


'<%#Eval("FieldNameInDataBase")%>'


if link button using



 




Thanks buddy


Tell me one thing that can i use  <%#Eval("FieldNameindatabase")%> in window.open function


Plz reply






Dear,


 


of course you can use like


window.open('<%#Eval("FieldNameindatabase")%>')



SomeOne please help how to bind eval in window.open


Regards 


Muhammad Arsalan Akhtar



Use LinkButton



Set OnClientClick property from RowDataBound Event


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = e.Row.FindControl("LinkButton1") as LinkButton;
string vchrEmbossLine=Convert.ToString(DataBinder.Eval(e.Row.DataItem,"vchrEmbossLine"));
lb.OnClientClick = string.Format("window.open('LoadBalance.aspx?EmbossLine={0}',null,'width=800,height=800');", vchrEmbossLine);
}
}









Thanks every one for reply


Regards 


Muhammad Arsalan Akhtar


[RESOLVED] Can I have different SelectMethods for the same DataSource


I have a DataSource that is bound to my gridview. There is a SelectMethod for this DataSource that calls a stored proc and populates this gridview.


I added a dropdown to filter the gridview. After filtering, I need to repopulate the gridview. Can I create a brand new stored proc based on the selectedValue from the dropdown and call this proc from a method and use this new method as SelectMethod for
the same DataSource? so I can repopulate the gridview based on filtering.


My problem is that when I added filtering, it broke sorting. I was using a DataSource to filter but in order for column sorting to take affect, I was told that I have to use DataSourceID (not DataSource) since the column sorting has been built into the program.
When I was using DataSource, I had to set DataSourceID to null (since I can't use both DataSource and DataSourceID), which fixed my filtering problem but broke column sorting in the gridview. I have to use DataSourceID in order for the column sorting to work.


Hope that makes sense. Coming from an MVC background, this really gets me.....


Thanks,

AM



Use same select method. Manipulate the parameter, query, stored procedure to filter data.

I created a new stored proc, a new select method and attached it to the same ObjectDataSource.


It is giving me the following error:


ObjectDataSource 'odsActions' could not find a non-generic method 'GetAudit' that has parameters: attID, reqID, plnID, scope.


GetAudit is the original method with parameters reqID, plnID, scope. It populates the gridview on page_load.


I added another method GetAuditLogFiltered with parameters: attID, reqID, plnID, scope.


I am not sure why it is looking for attID as parameter in GetAudit. What am I missing?


string SelectedVal = ddlAuditLogFilter.SelectedValue.ToString();


            if (!(SelectedVal == "-1"))

            {

                odsActions.SelectParameters.Clear();

                odsActions.TypeName = "Wf.Sparc.DAL.DbAccess";

                odsActions.SelectMethod = "GetAuditFiltered";

                odsActions.SelectParameters.Add("attID", SelectedVal.ToString());

                odsActions.SelectParameters.Add("reqID", reqID.ToString());

                odsActions.SelectParameters.Add("plnID", plnID.ToString());

                odsActions.SelectParameters.Add("scope", scope);

                gvActions.DataBind();


                gvActions.Visible = true;

                btnActionsExport.Visible = true;

            }

            else

            {

                odsActions.SelectParameters.Clear();

                odsActions.SelectParameters.Add("reqID", reqID.ToString());

                odsActions.SelectParameters.Add("plnID", plnID.ToString());

                odsActions.SelectParameters.Add("scope", scope);

                odsActions.Select();

            }


            if (gvActions.Rows.Count == 0)

            {

                gvActions.Visible = false;

                btnActionsExport.Visible = false;

            }


 





archnam



It is giving me the following error:


ObjectDataSource 'odsActions' could not find a non-generic method 'GetAudit' that has parameters: attID, reqID, plnID, scope.





Hi,


The error means ObjectDataSource is confused, try the links below for two possible solutions. 


http://kanthu.blogspot.com/2005/10/objectdatasource.html .


http://stackoverflow.com/questions/16641243/asp-net-objectdatasource-could-not-find-a-non-generic-method-that-has-parameters .


Hope it can help you.


Best Regards,

Amy Peng 





do your GetAudit method have those parameters?


[RESOLVED] Exporting datalist and gridview to excel


Hello Experts,


I am having one datalist and gridview within datalist control. I need to export both of them as report in excel sheet. Like below


sr.  Class  CreatedDate ModifiedDate


1     Class1   25/5/2013   25/5/2013


Students


Sr.  Name Address Bdate


1    Abc    test add  25/5/1990


2    DEF   test add 2  25/3/1991


sr.  Class  CreatedDate ModifiedDate


2     Class2   25/6/2013   25/6/2013


Students


Sr.  Name Address Bdate


1    Abc2    test add22  25/5/1990


2    DEF2   test add 22  25/3/1991


and so on.....


Here the class display is datalist and student display is gridview.


Please suggest how to achive that?


Thank you.




Refer bellow url


http://www.aspsnippets.com/Articles/Export-GridView-To-WordExcelPDFCSV-in-ASP.Net.aspx



Hi,


Please try to refer to the following code about export data to excel (use the gridview as an example):


protected void fillGrid()
{
string str = "SELECT [UNo], [EmpName], [Age],
convert(char,[dob],103) dob FROM [tbl_EmpDetails]";

myConnection = new SqlConnection(conn);
myConnection.Open();
myCommand = new SqlCommand(str, myConnection);
SqlDataAdapter mySQLDataAdapter;
myDataSet = new DataTable();
mySQLDataAdapter = new SqlDataAdapter(myCommand);
mySQLDataAdapter.Fill(myDataSet);
GridView1.DataSource = myDataSet;
GridView1.DataBind();
ViewState["dtList"] = myDataSet;
}

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillGrid();
}
}

Now, after binding a Gridview, data is ready to get exported to an Excel file. Click on a button named Export to Excel. Used FileInfo to get the information related to the file.


FileInfo FI = new FileInfo(Path);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid DataGrd = new DataGrid();
DataGrd.DataSource = dt1;
DataGrd.DataBind();

DataGrd.RenderControl(htmlWrite);
string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}

System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
stringWriter.ToString().Normalize();
vw.Write(stringWriter.ToString());
vw.Flush();
vw.Close();
WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());

The above code uses a WriteAttachment function which pushes the attachment to the user in the Response object. The following code shows the implementation of WriteAttachment:


public static void WriteAttachment(string FileName, string FileType, string content)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = FileType;
Response.Write(content);
Response.End();
}

Hope it can help you.


Best Regards,

Amy Peng 


[RESOLVED] Alphabetic Paging


Hi, Could you please help me on the issue of using the ASCII value of Georgian language characters. How can I change the english alphabet? I cannot retrive data since my contact list is in Georgian language. Here is the code:


public partial class alfabet : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["CurrentAlphabet"] = "ALL";
this.GenerateAlphabets();
this.BindDataList();
}
}

public class Alphabet
{
private string _value;
private bool _isNotSelected;

public string Value
{
get
{
return _value;
}
set
{
_value = value;
}
}

public bool isNotSelected
{
get
{
return _isNotSelected;
}
set
{
_isNotSelected = value;
}
}
}

private void GenerateAlphabets()
{
List alphabets = new List();
Alphabet alphabet = new Alphabet();
alphabet.Value = "ALL";
alphabet.isNotSelected = !alphabet.Value
.Equals(ViewState["CurrentAlphabet"]);
alphabets.Add(alphabet);
for (int i = 65; i <= 90; i++)
{
alphabet = new Alphabet();
alphabet.Value = Char.ConvertFromUtf32(i);
alphabet.isNotSelected = !alphabet.Value
.Equals(ViewState["CurrentAlphabet"]);
alphabets.Add(alphabet);
}
rptAlphabets.DataSource = alphabets;
rptAlphabets.DataBind();
}

private void BindDataList()
{
string conStr = ConfigurationManager
.ConnectionStrings["CompanyInfoEventsConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("spx_GetContacts");
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Alphabet", ViewState["CurrentAlphabet"]);
con.Open();
dlContacts.DataSource = cmd.ExecuteReader();
dlContacts.DataBind();
con.Close();

if (ViewState["CurrentAlphabet"].ToString().Equals("ALL"))
lblView.Text = "all Contacts.";
else
lblView.Text = "Contacts whose name starts with "
+ ViewState["CurrentAlphabet"].ToString();
}

protected void Alphabet_Click(object sender, EventArgs e)
{
LinkButton lnkAlphabet = (LinkButton)sender;
ViewState["CurrentAlphabet"] = lnkAlphabet.Text;
this.GenerateAlphabets();
this.BindDataList();
}



}







Hi,


The ASCII value of the alphabets A-Z is 65 - 90 same way for Georgian language you need to set appropriate value.


#The ASCll Table:

http://www.asciitable.com/ . 


And I think this article may help you:

http://www.c-sharpcorner.com/uploadfile/satyapriyanayak/alphabetic-paging-using-gridview-control/ .


Best Regards,

Amy Peng 



[RESOLVED] GridView column is hidden when export to excel exlcude the hidden column


I have a gridview, some of column is hidden but when i export to excel, in excel it still show the hidden column. May i know how to do it??


below is my sample script in App_Code:


public class GridViewExportUtil

{



    public static void Export(string fileName, GridView gv)

    {

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.ClearContent();

        HttpContext.Current.Response.ClearHeaders();

        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));



         using (StringWriter sw = new StringWriter())

        {

            using (HtmlTextWriter htw = new HtmlTextWriter(sw))

            {

                Table table = new Table();




                if (gv.HeaderRow != null)

                {

                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);

                    table.Rows.Add(gv.HeaderRow);

                }



                foreach (GridViewRow row in gv.Rows)

                {

                    GridViewExportUtil.PrepareControlForExport(row);

                    table.Rows.Add(row);

                    

                }



                if (gv.FooterRow != null)

                {

                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);

                    table.Rows.Add(gv.FooterRow);

                }



                table.RenderControl(htw);



                HttpContext.Current.Response.Write(sw.ToString());

                HttpContext.Current.Response.Flush();

                HttpContext.Current.Response.Close();

                HttpContext.Current.Response.End();

            }

        }

    }



    private static void PrepareControlForExport(Control control)

    {

        for (int i = 0; i < control.Controls.Count; i++)

        {

            Control current = control.Controls[i];

            if (current is LinkButton)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));

            }

            else if (current is ImageButton)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));

            }

            else if (current is HyperLink)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));

            }

            else if (current is DropDownList)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));

            }

            else if (current is CheckBox)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));

            }

            else if (current.Visible == false)

            {

                control.Controls.Remove(current);

            }

            if (current.HasControls())

            {

                GridViewExportUtil.PrepareControlForExport(current);

            }

        }

    }



Maybe you can do like this


GridView1.AllowSorting = false;
GridView1.Columns[2].Visible = false;
//export process
GridView1.Visible = true;
GridView1.AllowSorting = true;









oned_gk



Maybe you can do like this
GridView1.AllowSorting = false;
GridView1.Columns[2].Visible = false;
//export process
GridView1.Visible = true;
GridView1.AllowSorting = true;




Thank for your information. I have try to add in the below code, but the problem still same....any idea??

                for (int i = gv.Columns.Count - 1; i >= 0; i--)

                {

                    if (gv.Columns[i].Visible == false)

                    {

                        gv.HeaderRow.Cells[i].Visible = false;

                        gv.FooterRow.Cells[i].Visible = false;

                    }

                    gv.Columns[i].Visible = false;

                }



Hi lansishao,


I have checked your code and to me, the method PrepareControlForExport(Control control) needs some refinement, actually when u replace different controls like link-buttons, dropdowns etc with LiteralControl controls, there you should check the visibility
of the actual control, if actual control is visible then you should replace it with Literal otherwise no need to add it. Hopefully you got my point,


else if (current is CheckBox && current.Visible)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
// Controls has been replace with Literal and Literal is alwasy Visible :)
else if (current.Visible == false)
{
control.Controls.Remove(current);
}







Thanks 



Thank for your information. But actually i no so understand what you mean. Can you provide me some sample of code? thank you.



here it is,code id Bold and and under-lined


else if (current is CheckBox && current.Visible) // visibility check
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
// Controls has been replace with Literal and Literal is alwasy Visible :)
else if (current.Visible == false)
{
control.Controls.Remove(current);
}



Thank you...but after i try ur method add on the code, after export the data to excel, those hidden column still show....
Cry



can you share the ASPX page code, where you are hiding the grid columns, like grid item template and specially the hidden column template.


thanks



this is sample as below:




        EnableModelValidation="True" CellPadding="4" ForeColor="#333333" GridLines="Vertical"             

        style="font-family: 'Century Gothic'; font-size: small" Width="98%" ShowFooter="True"

        OnPreRender = "gv_PreRender" OnRowDataBound = "gv_RowDataBound">

   

   

                   
                        ItemStyle-HorizontalAlign="Right"/>

                       

                       

                           

                       


                       


                   
                        ItemStyle-HorizontalAlign="Right"/>

                       

                       

                           

                       


                       


   



change your hidden item template as follow,




ItemStyle-HorizontalAlign="Right"/>


Visible = "false" runat="server" Text='<%#Eval("Jan") %>'>


ItemStyle-HorizontalAlign="Right"/>


Visible = "false" runat="server" Text='<%#Eval("Feb") %>'>










thanks for you...i have set the label to visible and the problem solved..


because it have many page...may i know any best way to amend the code what i post before?



it is good to know that your problem solved, please mark the thread as answered if it helps you Innocent


Secondly, in your code you are checking at control Level that if it is visible or not, your code line


if(control.visible==false)

so you have to apply the visible attribute to every control in every grid in every page, other wise chagne the code to export data, that change of code, may introduce other problems :) 




[RESOLVED] ImageHandling error


Hi,


I have some problems loading my image file into the gridview control.


Please see screenshot: http://imageshack.us/photo/my-images/708/92zh.jpg/


Image handling ashx file:


public void ProcessRequest(HttpContext context)

{

objCmd.CommandText = "Select ImgSrc from M_DMemPict" + " where ImageId=@ImageId";

objCmd.CommandType = System.Data.CommandType.Text;

objCmd.Connection = objConn;

SqlParameter ImageID = new SqlParameter("@ImageId", System.Data.SqlDbType.Int);

ImageID.Value = context.Request.QueryString["img"];

objCmd.Parameters.Add(ImageID);

objConn.Open();

SqlDataReader dReader = objCmd.ExecuteReader();

dReader.Read();

context.Response.BinaryWrite((byte[])dReader["ImgSrc"]);

dReader.Close();

objConn.Close();


context.Response.ContentType = "image/jpeg";

context.Response.AppendHeader("Content-Disposition", "attachment; filename=test.JPG");

//context.Response.TransmitFile(@"D:\\test.jpg");

//context.Response.End();


}


Please help, thanks.



Check your query first at the Database , did it returns the column "ImageId" or not.



this is the case of since your query doest not returns the column ImageId



@Rjk_P,


my query is correct however could you please correct this syntax from the gridview control using templatefield tag.



ImageUrl='<%# "~/ImgHandler.ashx?id=" + Eval("ImageId")%>'/>


The image is not displaying on the gridview. 


Thanks.



Your are passing id as parmenter and taking img as  request context querysting value at server side. Change it and try..



Hi,


The error is DataBinding:System.Data.DataRowView" does not contain a property with the name 'ImageId'.


So please try to check if you have a column named 'ImageId', Or you have mistake the name of the column.


Hope it can help you.


Best Regards,

Amy Peng 


[RESOLVED] Grid View Update


Dear Friends,


                 I am inserting data from grid using button control. Hence there is no Button controls inside the grid.


When loading the grid at first time initially first row will be there and if i click the "Add" button means rows will create. For this my code part is,


#region SetInitialRowforTransfer

///



/// SetInitialRowforTransfer

///


private void SetInitialRowforTransfer()

{

try

{

DataTable dt = new DataTable();


DataRow dr = null;


dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));


dt.Columns.Add(new DataColumn("Column1", typeof(string)));


dt.Columns.Add(new DataColumn("Column2", typeof(string)));


dt.Columns.Add(new DataColumn("Column3", typeof(string)));


dt.Columns.Add(new DataColumn("Column4", typeof(string)));


dt.Columns.Add(new DataColumn("Column5", typeof(string)));


dt.Columns.Add(new DataColumn("Column6", typeof(string)));


dt.Columns.Add(new DataColumn("Column7", typeof(string)));


dr = dt.NewRow();


dr["RowNumber"] = 1;


dr["Column1"] = string.Empty;


dr["Column2"] = string.Empty;


dr["Column3"] = string.Empty;


dr["Column4"] = string.Empty;


dr["Column5"] = string.Empty;


dr["Column6"] = string.Empty;


dr["Column7"] = string.Empty;


dt.Rows.Add(dr);


//dr = dt.NewRow();



//Store the DataTable in ViewState


ViewState["CurrentTableforTransfer"] = dt;



gvContact.DataSource = dt;


gvContact.DataBind();

}

catch (Exception ex)

{


throw ex;

}




}

#endregion


#region AddNewRowToGridforTransfer

///



/// AddNewRowToGridforTransfer

///


private void AddNewRowToGridforTransfer()

{

try

{


int rowIndex = 0;



if (ViewState["CurrentTableforTransfer"] != null)

{


DataTable dtCurrentTable = (DataTable)ViewState["CurrentTableforTransfer"];


DataRow drCurrentRow = null;


if (dtCurrentTable.Rows.Count > 0)

{


for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)

{


//extract the TextBox values


TextBox box1 = (TextBox)gvContact.Rows[rowIndex].Cells[1].FindControl("txtTransferPLaceFrom");


TextBox box2 = (TextBox)gvContact.Rows[rowIndex].Cells[2].FindControl("txtDesignTransfer");


TextBox box3 = (TextBox)gvContact.Rows[rowIndex].Cells[3].FindControl("txtTansferDate");


TextBox box4 = (TextBox)gvContact.Rows[rowIndex].Cells[4].FindControl("txtToPlace");


TextBox box5 = (TextBox)gvContact.Rows[rowIndex].Cells[5].FindControl("txtJoiningDate");


TextBox box6 = (TextBox)gvContact.Rows[rowIndex].Cells[6].FindControl("txtTransferReason");


TextBox box7 = (TextBox)gvContact.Rows[rowIndex].Cells[7].FindControl("txtTransferemail");



drCurrentRow = dtCurrentTable.NewRow();


drCurrentRow["RowNumber"] = i + 1;



dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;


dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;


dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;


dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;


dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;


dtCurrentTable.Rows[i - 1]["Column6"] = box6.Text;


dtCurrentTable.Rows[i - 1]["Column7"] = box7.Text;



rowIndex++;


}


dtCurrentTable.Rows.Add(drCurrentRow);


ViewState["CurrentTableforTransfer"] = dtCurrentTable;



gvContact.DataSource = dtCurrentTable;


gvContact.DataBind();


}


}


else

{


Response.Write("ViewState is null");


}



//Set Previous Data on Postbacks


SetPreviousDataforTransfer();

}

catch (Exception ex)

{


throw ex;

}


}

#endregion


#region SetPreviousDataforTransfer

///



/// SetPreviousDataforTransfer

///


private void SetPreviousDataforTransfer()

{


try

{

int rowIndex = 0;


if (ViewState["CurrentTableforTransfer"] != null)

{


DataTable dt = (DataTable)ViewState["CurrentTableforTransfer"];


if (dt.Rows.Count > 0)

{


for (int i = 0; i < dt.Rows.Count; i++)

{


TextBox box1 = (TextBox)gvContact.Rows[rowIndex].Cells[1].FindControl("txtTransferPLaceFrom");


TextBox box2 = (TextBox)gvContact.Rows[rowIndex].Cells[2].FindControl("txtDesignTransfer");


TextBox box3 = (TextBox)gvContact.Rows[rowIndex].Cells[3].FindControl("txtTansferDate");


TextBox box4 = (TextBox)gvContact.Rows[rowIndex].Cells[4].FindControl("txtToPlace");


TextBox box5 = (TextBox)gvContact.Rows[rowIndex].Cells[5].FindControl("txtJoiningDate");


TextBox box6 = (TextBox)gvContact.Rows[rowIndex].Cells[6].FindControl("txtTransferReason");


TextBox box7 = (TextBox)gvContact.Rows[rowIndex].Cells[7].FindControl("txtTransferemail");




box1.Text = dt.Rows[i]["Column1"].ToString();


box2.Text = dt.Rows[i]["Column2"].ToString();


box3.Text = dt.Rows[i]["Column3"].ToString();


box4.Text = dt.Rows[i]["Column4"].ToString();


box5.Text = dt.Rows[i]["Column5"].ToString();


box6.Text = dt.Rows[i]["Column6"].ToString();


box7.Text = dt.Rows[i]["Column7"].ToString();



rowIndex++;


}


}


}


}

catch (Exception ex)

{


throw ex;

}

}

#endregion


#region ButtonAddfoTransfer_Click

///



/// ButtonAddfoTransfer_Click

///


///

///

protected void ButtonAddfoTransfer_Click(object sender, EventArgs e)

{


AddNewRowToGridforTransfer();


}

#endregion



Then i can insert the data by using following Insert code,


#region InsertGridTransferDetails


public void InsertGridTransferDetails(int sid)

{

BO_ObjSupplierMaster = new BO_Supplier_Master();

BE_ObjSupplierContact = new BE_Supplier_Contact();

try

{


foreach (GridViewRow row in gvContact.Rows)

{


TextBox txtplacefrm = (TextBox)row.FindControl("txtTransferPLaceFrom");

TextBox txtdesigntransfer = (TextBox)row.FindControl("txtDesignTransfer");

TextBox txttransferdate = (TextBox)row.FindControl("txtTansferDate");

TextBox txttoplace = (TextBox)row.FindControl("txtToPlace");

TextBox txtjoindate = (TextBox)row.FindControl("txtJoiningDate");

TextBox txttransferreason = (TextBox)row.FindControl("txtTransferReason");

TextBox txttransferemail = (TextBox)row.FindControl("txtTransferemail");


BE_ObjSupplierContact.Sup_Con_Lname1 = txtplacefrm.Text;

BE_ObjSupplierContact.Sup_Con_Mname1 = txtdesigntransfer.Text;

BE_ObjSupplierContact.Sup_Con_Fname1 = txttransferdate.Text;


BE_ObjSupplierContact.Sup_Con_Title1 = txttoplace.Text;

BE_ObjSupplierContact.Sup_Con_Telephone1 = txtjoindate.Text;

BE_ObjSupplierContact.Sup_Con_Mob1 = txttransferreason.Text;

BE_ObjSupplierContact.Sup_Con_Email1 = txttransferemail.Text;


BE_ObjSupplierContact.Sup_Master_Key1 = Convert.ToInt16(sid);


BO_ObjSupplierMaster.InsertSupplierContact(BE_ObjSupplierContact);


}





}

catch (Exception ex)

{


throw ex;

}

}

#endregion



Front end code is,



BorderColor="#A01E1E" Width="85%" HeaderStyle-Height="40px" RowStyle-Height="30px"

RowStyle-BorderColor="#A01E1E" runat="server" ShowFooter="true" AutoGenerateColumns="false">
















































































Text="Add" />









Now i want to Update the record. How can i bind the data to the grid. Please guide me to bind the data.



hey, once you add a new row to datatable, you can rebind the datatable to gridview again as


gvContact.DataSource = dtCurrentTable;


gvContact.DataBind();



and it will automatically update record



Hi,


Goto following link it has shown insert,update and delete inline.


http://www.codeproject.com/Articles/24085/Insert-Update-Delete-with-Gridview-Simple-Way


[RESOLVED] Export ExcelFile to grid View


Hi, I want to import an excel file(file name: tp30.xls, having one sheet name: tp30) in a gridView. Every time I get a Exception....


Syntax error (missing operator) in query expression 'Valuated stock'.


near the line.....    da.Fill(ds);    ( or, da.Fill(ds,"[tp30$]"); )


here is my codes........


protected void Button2_Click(object sender, EventArgs e)
{
string connString = "";
string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower();
string path = FileUpload1.PostedFile.FileName;
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT Material,Valuated stock FROM [tp30$]";
OleDbConnection conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
da.Dispose();
conn.Close();
conn.Dispose();
}
}

The aspx code.....
































It simply does not understand that Valuated stock is one word and not 2 different names. 


Try


string query = "SELECT Material,[Valuated stock] FROM [tp30$]";


I have Solve it!!!



Hi San,

Try this

 string query = "SELECT Material,[Valuated stock] FROM [tp30$]";



Sql didn't allow space between the name of column.so you need to put the name in square bracket.

hope this will help you out .

[RESOLVED] Validations controls causing problems


hello 


i am designing a form where there are some textboxes along with validations on the form and user is submiting data in the textboxes on click of save button.


also there is a datagrid in bottom of the form where data from table in the database is showing and ser is able to update the data in the grid delete row, update.


sometimes it happens that user just update or delete rows from the grid and don't enter the data in the textboxes which are also present on the form along with the validations and when user clicks update or delete button on grid that action don't takes place
instead validaions control shows errors. how to handel this problem?


thanx in advance 



Specify
ValidationGroup
property


I guess (not sure) if you use ValidationGroup only on Form validation, it will work. Set ValidationGroup property to all validators in Form and Also set ValidationGroup property of button


Or you can set different validation groups for form and gridview.


Regards



You can set other buttons causesvalidation="false"

[RESOLVED] Search/Filter GridView - SQL Stored Proc or DataTable (Efficiency)?


I have a GridView containing Employee data and want to be able to search/filter the results.


What is the most efficient way to do this out of the options below (or maybe another option)?


1. SQL Stored Proc with various Parameters (EmployeeID, FirstName, LastName, Manager, etc) meaning that only matched results are returned to the GridView.


2. DataTable containing the entire Employee dataset (approx 3,000 employees) from a simple SQL Stored Proc that returns all employee records. Handle the filtering of the DataTable in code behind.


My gut feeling is that option 1 would be more efficient (in a way) because you are only passing a limited number of employee records from the [seperate] database server to the app/web server. Also, it means that large DataTables will not be held in memory.


On the other hand, option 1 would potentially result in many more calls to the database server, whereas option 2 would be a one time call.



I would still prefer option 1... since it will be clean, more maintainable and typical search operation is generally not invoked very repetadely


also, if number of users grows in future then, for search operation by every user, it will store data in server memory... so, not a good approach in terms of scalability


hope this helps...


[RESOLVED] FINDING THE TOOL


IT IS SIMILAR TO GRIDVIEW WITH COLUMNS AS ROWS AND WITH A HORIZONTAL SCROLL BAR.  THE IMAGE WAS IN VB PROJECT. I WANT IN ASP.NET




[RESOLVED] Gridview freeze Header in asp.net


I want freeze Gridview header for all the forms in my Application.  


[RESOLVED] ForeColor of a gridview row &#39;s text, if that row is disabled.


How to change the ForeColor of a gridview's row 's text, if that row is disabled.

(some of the rows are enabled and some are disabled.)


I gave this code in the item the itemDatabond


e.Item.ForeColor = System.Drawing.Color.Blue

e.Item.BackColor = System.Drawing.Color.LightGray

e.Item.Enabled = False




But it is not working because that row is disabled and very hard to read the text in the disabled row.


Thanks




But it is not working because that row is disabled and very hard to read the text in the disabled row.


What does this mean?


If you are using IE, then it changes the color based on if a control is disabled.  If you lookin in FF or Chrome for example, the your colors will take.


You can set the row to ReadOnly instead of Disabled, then your colors should take.



Try this CSS :


disabled style has it's own than normal style


[disabled]
{
color:#933;
background-color:#ffc;
}

http://www.w3schools.com/cssref/sel_disabled.asp



meaning the code I added is working. ( it is now showing the blue forecolor for the disabled row's text)


e.Item.ForeColor = System.Drawing.Color.Blue

e.Item.BackColor = System.Drawing.Color.LightGray

e.Item.Enabled = False



And i did not see any readonly property for e.Item for the row either. I am trying to do it throgh the code rather than stylesheet.


Any other suggestions?





Jaypal



And i did not see any readonly property for e.Item for the row either. I am trying to do it throgh the code rather than stylesheet.


Any other suggestions?





Hi,


There is no readonly property for the row, you have to set the cells in the row to as readonly:


TextBox chkVal = ((TextBox)row.FindControl("TextBox1"));

chkVal.ReadOnly = false;


I try your way to set the forecolor for the disable row, it can work well.


Hope it can help you.


Best Regards,

Amy Peng 




[RESOLVED] Change selected datagrid row (also in database)


Hi,


I have a .In it there are   like










I want to change values under the "is  active column" from "Yes" to "No", when i select rows and click delete button.


(Note:I am not using Gridview)


Thanks



Hi,


you can post your query on telerik forum  


http://www.telerik.com/community/forums.aspx



one simple solution can be, just catch the delete event of the Grid and do what ever you want to do, in that delete event.


thanks 



Hi,


The following threads may give you some idea, but you had better post your question in
telerik forum:


http://stackoverflow.com/questions/9639762/select-row-in-radgrid-button-click .


http://stackoverflow.com/questions/7420439/telerik-getting-selected-id-get-data-from-radgrid-selected-item .


Hope it can help you.


Best Regards,

Amy Peng 



[RESOLVED] From Visual Studio in “design view”, is possible to have the correspondig lines of code highlighted in “source view”?


I use VS2010 with GridView, FormView ecc...


I frequently switch from Design View (in which for example I am visually editing something inside a FormView EditItemTemplate), to Source View.


Note that this happen when I am editing something inside a EditItemTemplate


So, for example if in Design View I have a TextBox selected, when I switch to Source View I'd like to have ONLY the corresponding lines selected, instead VS2010 highligh ALL the FormView EditItemtemplate code, from start to finish (which can be 1000 lines
long!).


Is possible or not to instruct VS to select only the relevant lines?




No it is not posible.



Because gridview is one control and you are placing another controls inside it. So it is consider as part fo grid view so it will select whole grid view. And also you can not directly access that control in code behind just because of same reason.




Wait!


Now it is functioning correctly!


From Design view:



  1. I select an TextBox --> ... is selected in source view
  2. I click in a cell -->
  3. I highligh a full table row in design --> the code inside ... is selected in source, wonderful!


From source view:



  1. I click wherever in a line inside the whole table is highlighted in design view
  2. I click inside a the control is highlighted in design view

  3. WONDERFUL!!! Surprised


    So, what the hell has got messed before, and what I have done in the meantime that reset things?


    (In the meantime I have close and reopend VS (not working), rebuild solution, refactored code, reformatted code, changed formatting tag options, ecc...)



    Arrghhh!!!


    I edited the code from the Source view, removing a

    line, the VS asked me to refresh the view, claiming that Design view is out of sync with Source view.


    I clicked to synchronize view, and now it's not functioning anymore!!! Yell


    I thought it could be because some background VS task didn't have yet enough time to complete, so I waited ... but after something like 10 minutes of wait it's not working yet....


    So, I clicked undo to insert the

    lines back... and (not so surprisingly) the highlight works again!!!


    What is happening???



    PS: Important info. If instead I remove the

    line from the Design view, via mouse dx popup menu-->Delete rows-->Delete row the Source/Design remains in synch and the highlight functionality continue working Undecided



    Up to now I have found this workaround... that seems to be working :-)


    You have manually edited the source code, so messing up the synchronize with design view...!



    1. Select a control in Design view
    2. Change something in the Properties window, (for example set width=100px, or toggle the Enabled property)
    3. WAIT.... (your change forces VS to update the source code!)
    4. After some time (something like 5-10 seconds for my slow machine ;-)), VS updates the code, adding/changing the relevant code 
    5. And now the bidirectional highlight functionality works again!
    6. Remember to Change back/Toggle the modified property Tongue Out