How to access controls inside GridView?
1. If the controls is in a TemplateField, and use EditItemTemplate for editing, FooterTemplate for inserting records
< asp:templatefield sortexpression="name" headertext="Name" >
< ItemTemplate > < %# Eval("name") %> < / ItemTemplate >
< FooterTemplate > < asp:TextBox id="txtInsertName" runat="server">< / asp:TextBox > < / FooterTemplate>
< EditItemTemplate > < asp:TextBox id="txtEditName" runat="server"> < / asp:TextBox > < / EditItemTemplate >
< /asp:templatefield>
....
< asp:TemplateField HeaderText="Action">
< ItemTemplate>
< asp:LinkButton id="btnEdit" Runat="server" Text="Edit" CommandName="Edit">< /asp:LinkButton>
< asp:LinkButton id="btnDelete" Runat="server" Text="Remove" CommandName="Delete">< /asp:LinkButton>
< /ItemTemplate>
< EditItemTemplate>
< asp:LinkButton id="btnSave" Runat="server" Text="Save" CommandName="Update">< /asp:LinkButton>
< asp:LinkButton id="btnCancel" Runat="server" Text="Cancel" CommandName="Cancel">< /asp:LinkButton>
< /EditItemTemplate>
< FooterTemplate>
< asp:LinkButton ID="btnInsert" Runat="server" Text="Insert" CommandName="Insert">< /asp:LinkButton>
< /FooterTemplate>
< /asp:TemplateField>
a. Initial values: In RowCreated event,
protected void dgContact_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
if ((e.Row.RowState & DataControlRowState.Edit) != 0) {
int index = e.Row.RowIndex;
IContact contact = contacts[index];
((TextBox)e.Row.FindControl("txtEditName")).Text = contact.name;
...
}
}
}
b. Updating: OnRowUpdating event,
protected void dgContact_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = dgContact.Rows[e.RowIndex];
contact.name = ((TextBox)row.FindControl("txtEditName")).Text;
...
}
c. Insert: OnRowCommand
protected void dgContact_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName) {
case "Insert":
GridViewRow row = dgContact.FooterRow;
contact.name = ((TextBox)row.FindControl("txtInsertName")).Text;
...
}
d. Delete: OnRowDeleting Event
protected void dgContact_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
string email = dgContact.DataKeys[e.RowIndex].Value.ToString();
...
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment