I have a requirement wherein, I have to create grid view dynamically (i.e. setting the datasource from code behind).
To implement the insert functionality on gridview, I am using the footer row, I am dynamically creating the footerRow through following code on _RowDataBound event:
CheckBox EnabledCheckbox = new CheckBox();
TextBox NameTextbox = new TextBox();
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[1].Controls.Add(NameTextbox);
e.Row.Cells[2].Controls.Add((EnabledCheckbox));
}
The footer template got Save button which is added through aspx:
<FooterTemplate>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"/>
</FooterTemplate>
Now onclick of “Save” button, the page gets postback and the Textbox and checkbox value comes as null.
I tried moving the code from Page_load to Page_init but that creates problem in update functionality.
Let me know how I can handle this? or please suggest if there is any other better way to implement this.
SOLUTION1 :
As I understood your requirement with grid view , I think you should use following steps.
1. Use RowCreated event to create the footer with checkbox and text box instead of RowDataBound event.
2. As every control in grid view is child control for grid view so button click will be handle by grid view events(e.g. RowCommand event )
Use this code in your aspx
<FooterTemplate>
<asp:Button ID="btnSave" runat="server" Text="Save" CommandName="SAVE" "/>
</FooterTemplate>
3. Use gridView_RowCoomand for handling the button click and save the inserted value.
e.g.
gridview_RowCommand(…………….)
{
if (e.CommandName == "SAVE")
{
//Capture user input from footer row
//Insert in to database
}
}
This code will work for your requirement . Please let me know if you find any difficulty in implementation.
I added the footer row on Pre_init() like this –
ReplyDeleteGridView1.RowCreated += delegate(object dsender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[1].Controls.Add(NameTextbox);
e.Row.Cells[2].Controls.Add((EnabledCheckbox));
}
};
regadrds,
amitha,