user6628729 user6628729 - 2 months ago 21
ASP.NET (C#) Question

display gridview on button click

First i try to displaly gridview on pageload so girdveiw succesffully displayed now i try to display when click on button i try below code but grid not visible

Code

DataTable dt = new DataTable();
public DataTable info(string id)
try
{
Entities2 wr = new Entities2();
List<spv_Result> sv = wr.spvec(id).ToList();
dt.Columns.Add("RowNumber", typeof(int));
foreach (var c in sv)
{
dt.Rows.Add(c.RowNumber);
}
return dt;
}
catch (Exception ex)
{
throw new Exception();
}

}

protected void Button1_Click(object sender, EventArgs e)
{
info(id);
GridView1.DataSource = dt;
GridView1.DataBind();

}


there is data in dt but gridview not display

<asp:GridView ID="GridView1" runat="server" class="display nowrap"
Width="100%" CellPadding="0"
Font-Names="Verdana" BackColor ="White" BorderColor="#CCCCCC" BorderStyle="None"
BorderWidth="1px" Font-Size="9pt">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />




any solution?

Answer

I think "dt" has no value in below line for button click event.

GridView1.DataSource = dt;

Try this:

protected void Button1_Click(object sender, EventArgs e)
{
    GridView1.DataSource = info(id);
    GridView1.DataBind();
}

or 

protected void Button1_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt = info(id);
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

Here, "info" method directly returns datatable, then values are assigned to Gridview.