In actual application, girdview dynamically loads columns based on certain conditions. This demo demonstrates how to load columns and bind data.
In actual application, you can make modifications accordingly.
HTML:
<%... @ Page Language = "C #" autoeventwireup = "true" codefile = "PostBack. aspx. cs" inherits = "PostBack" %>
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Asp: gridview id = "gridview1" runat = "server" autogeneratecolumns = "false">
<Columns>
<Asp: templatefield>
<Itemtemplate>
<Asp: checkbox id = "Chk" runat = "server"/>
</Itemtemplate>
</ASP: templatefield>
</Columns>
</ASP: gridview>
<Asp: button id = "btngetfield" runat = "server" text = "getfield"
Onclick = "btngetfield_click"/> <br/>
<Asp: ListBox id = "list" runat = "server" Height = "200px" width = "200px"> </ASP: ListBox>
</Div>
</Form>
</Body>
</Html>
CS:
Public partial class PostBack: system. Web. UI. Page
...{
Protected void page_load (Object sender, eventargs E)
...{
If (! Ispostback)
...{
Createview ();
Setbind ();
}
}
Public void createview ()
...{
Boundfield DC1 = new boundfield ();
Dc1.datafield = "gwid ";
Dc1.headertext = "Steel Network No ";
Dc1.visible = true;
Boundfield DC2 = new boundfield ();
Dc2.visible = true;
Dc2.datafield = "machtype ";
Dc2.headertext = "Machine Model ";
Boundfield DC3 = new boundfield ();
Dc3.visible = true;
Dc3.datafield = "isok ";
Dc3.headertext = "current status ";
Gridview1.columns. Add (DC1 );
Gridview1.columns. Add (DC2 );
Gridview1.columns. Add (DC3 );
}
Public void setbind ()
...{
String connstr = configurationmanager. connectionstrings ["connstr"]. tostring ();
Using (sqlconnection conn = new sqlconnection (connstr ))
...{
Conn. open ();
String SQL = "select top 10 * From allinfor ";
Sqldataadapter Ada = new sqldataadapter (SQL, Conn );
Dataset DS = new dataset ();
Ada. Fill (DS );
Gridview1.datasource = Ds. Tables [0];
Gridview1.databind ();
}
}
Protected void btngetfield_click (Object sender, eventargs E)
...{
For (INT I = 0; I <gridview1.rows. Count; I ++)
...{
Checkbox chk = gridview1.rows [I]. findcontrol ("Chk") as checkbox;
If (chk. Checked = true)
...{
List. Items. Add (gridview1.rows [I]. cells [2]. Text );
}
}
}
}