Gridview problem in Binding
My requirement is to dynamically generate columns (Bound and Template Columns as required) in GridView control. So I need to dynamically bind the controls at runtime. I need to do a bulk update to the database from the GridView.
I am facing problems in binding the control dynamically. When I dynamically create a text box and bind it to a GridView, during the update the value of the textbox is not properly passed to the ControlParamter of SqlDataSource control which will update the database. The values updated to the database are null.
Initially I used the Page_Load method to generate the controls in GridView and later changed it to Page_Init in order to handle the post back issues with the dynamically created textbox.
Please suggest a solution for this problem.
I am attaching the source code which dynamically binds the controls to the GridView at runtime.
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
//Creates a new label control and add it to the container.
Label lbl = new Label(); //Allocates the new label object.
lbl.Text = _columnName; //Assigns the name of the column in the lable.
container.Controls.Add(lbl); //Adds the newly created label control to the container.
break;
case ListItemType.Item:
//Creates a new text box control and add it to the container.
TextBox tb1 = new TextBox(); //Allocates the new text box object.
tb1.DataBinding += new EventHandler(tb1_DataBinding); //Attaches the data binding event.
tb1.ID = _columnName;
tb1.Columns = 15; //Creates a column with size 4.
//tb1.Text = _dr[_columnName].ToString();
container.Controls.Add(tb1); //Adds the newly created textbox to the container.
break;
case ListItemType.AlternatingItem :
//Creates a new label box control and add it to the container.
Label lb1 = new Label(); //Allocates the new label object.
container.Controls.Add(lb1); //Adds the newly created label to the container.
break;
case ListItemType.EditItem:
TextBox tb2 = new TextBox(); //Allocates the new text box object.
tb2.DataBinding += new EventHandler(tb1_DataBinding); //Attaches the data binding event.
tb2.ID = _columnName;
tb2.Columns = 15; //Creates a column with size 4.
tb2.ReadOnly = false;
container.Controls.Add(tb2); //Adds the newly created textbox to the container.
break;
case ListItemType.Footer:
CheckBox chkColumn = new CheckBox();
chkColumn.ID = "Chk" + _columnName;
container.Controls.Add(chkColumn);
break;
}
}
/// <summary>
/// This is the event, which will be raised when the binding happens.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void tb1_DataBinding(object sender, EventArgs e)
{
TextBox txtdata = (TextBox)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
txtdata.Text = dataValue.ToString();
}
}
|