4
Answers

how to bind dynamic gridview i.e AutoGenerateColumns=true

Sandeep Kumar

Sandeep Kumar

3y
586
1

i have a sp,which  return dyanimic columns name ,and i want bind it in gridview,how

please help me as soon as possible

Answers (4)
3
Sachin Singh

Sachin Singh

11 55.8k 87.3k 3y
until you specify the column names in GridView explicitly, the GridView is dynamic anyway. So, just call your SP and bind the result to GridView.
 
  1. public void BindGrid()  
  2. {  
  3. using (SqlConnection con = new SqlConnection("Data Source=SACHIN-PC\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"))  
  4.   {  
  5.     SqlDataAdapter da = new SqlDataAdapter("spGetEmployee", con);  
  6.     da.SelectCommand.CommandType = CommandType.StoredProcedure;  
  7.     DataSet ds = new DataSet();  
  8.     dataAdapter.Fill(ds);  
  9.     GridView1.DataSource = ds;  
  10.     GridView1.DataBind();  
  11.   }  
Note:- As a best practise, Always stored connection string in config file and retrieve from there
  1. // considering your connection string is stored in config file  
  2. string cs=ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;  
 
3
Arnab Mukherjee

Arnab Mukherjee

461 3.1k 161.7k 3y
Hi, If you have the datatable, simply bind it with gridview.
 
GridView1.DataSource = datatable;
GridView1.DataBind();
 

2
Sandeep Kumar

Sandeep Kumar

1k 689 68.1k 3y
i have datatable ,how to bind it in dynamic gridview
2
Arnab Mukherjee

Arnab Mukherjee

461 3.1k 161.7k 3y

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=*******Initial Catalog=*******;Persist Security Info=True;User ID=*******;Password=*******" ></asp:SqlDataSource>
<div>
<asp:TextBox ID="SqlQueryTextBox" runat="server" ></asp:TextBox>
<asp:Button ID="ExecuteButton" OnClick="ExecuteButton_Click" runat="server" Text="Execute"/>
</div>
<div>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="true" />
</div>
 
protected void ExecuteButton_Click(object sender, EventArgs e)
{
SqlDataSource1.SelectCommand = SqlQueryTextBox.Text;
GridView1.DataBind();
}