Sometimes, it may be a requirements to create dynamic asp.net controls to be added on page. Gridview is such one control that is often required to show data in a defined format. Here is the code for this to be accomplished.
//create a gridview object
dGv = new GridView();
//create a template field to contain the checkbox control
TemplateField template = new TemplateField();
//mytemplate is customized class for adding checkbox that implements ITemplate(required)
template.ItemTemplate = new MyTemplate();
dGv.Columns.Add(template);
//create a button & add it to gridview
ButtonField btn = new ButtonField();
btn.ButtonType = ButtonType.Button;
btn.Text = "test button";
dGv.Columns.Add(btn);
//get a simple table to be bound
dGv.DataSource = MyTable.SimpleTable();
dGv.DataBind();
//add gridview to page
Page.Form.Controls.AddAt(0, dGv);
//add an EventListener after postback
dGv.RowCommand += dgv_RowCommand;
Here MyTable.SimpleTable() returns a data table. it may either a data table from your database or a dynamically & melodramatically created.
A little tricky part is the itemp template creation. You need to creat your own class that implements ITemplate(an interface). Here is a simple example:
public class MyTemplate : ITemplate
{
public MyTemplate()
{
}
//required function to be implemented
public void InstantiateIn(Control control)
{
//add the checkbox to template
CheckBox chkbx = new CheckBox();
chkbx.ID = "chkbx";
control.Controls.Add(chkbx);
}
}
If you have a button/url link on your grid (in this example, a button column exist), the last line
dGv.RowCommand += dgv_RowCommand;
adds a handler. You can handle it as follows:
protected void dgv_RowCommand(object sender, GridViewCommandEventArgs e)
{
//get the row no that caused the postback
int i = Convert.ToInt32(e.CommandArgument);
//check each checkbox whether they are checked
int count = 0;
string test = "";
//iterate every row
foreach (GridViewRow row in dGv.Rows)
{
//work with controls & cells
CheckBox temp = row.FindControl("chkbx") as CheckBox;
test = row.Cells[0].Text;
if(temp.Checked)
{
count++;
}
}
}
You can extend this simple example to fullfill your needs.
Subscribe to:
Post Comments (Atom)










0 comments:
Post a Comment