havin havin - 1 year ago 50
Vb.net Question

Editing GridView For dynamically generated Field

My GridView is as follows

It has EmptyDatatemplate and Command Field

<asp:GridView ID="AGridView" runat="server" AutoGenerateColumns="true" style="table-layout:fixed;" Width="2000px" RowStyle-HorizontalAlign="Left">
<EmptyDataTemplate>
&nbsp;
</EmptyDataTemplate>
<asp:CommandField ShowEditButton="True" ItemStyle-Width="80px" EditText="Edit">
<ItemStyle Font-Bold="true" Font-Size="Small" />
<HeaderStyle CssClass="AAddOn" />
</asp:CommandField>
</asp:GridView>


GridView Looks like

Name Age Country
A 10 NNN Edit
B 23 NNN Edit


Now if i click on edit i need only Age Column to be edited

If i give AGridView.EditIndex = e.NewEditIndex entire row is edited

In codebehind

Private Sub AGridView_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles AGridView.RowEditing
Try
AGridView.EditIndex = e.NewEditIndex

AGridView.DataSource = SessionItems.ADataset.Tables("AHello")
AGridView.DataBind()

Catch ex As Exception
SetErrorMsg(ex.Message.ToString, "Error")
End Try
End Sub

Answer Source

That's simple. Whatever the columns you don't want editable, just add those in DataKeyNames property of grid. Try this.

<asp:GridView ID="AGridView" runat="server" AutoGenerateColumns="true"  style="table-layout:fixed;" Width="2000px"   RowStyle-HorizontalAlign="Left" DataKeyNames = "Name,Country" >
        <EmptyDataTemplate>
           &nbsp;
       </EmptyDataTemplate>
        <asp:CommandField ShowEditButton="True" ItemStyle-Width="80px" EditText="Edit">
         <ItemStyle Font-Bold="true" Font-Size="Small" />
          <HeaderStyle CssClass="AAddOn" />
         </asp:CommandField>
  </asp:GridView>


    Private Sub AGridView_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles AGridView.RowEditing
                Try

                  Dim colsToNotEdit As List<string>

//C# code 

        for (int i = 0; i < AGridView.HeaderRow.Cells.Count; i++)
    {
        if(grdToDisplay.HeaderRow.Cells[i].Text !="age")
          colsToNotEdit.Add(grdToDisplay.HeaderRow.Cells[i].Text);
    }
            AGridView.DataKeyNames = colsToNotEdit.ToArray()
     AGridView.EditIndex = e.NewEditIndex

                    AGridView.DataSource = SessionItems.ADataset.Tables("AHello")
                    AGridView.DataBind()

                Catch ex As Exception
                    SetErrorMsg(ex.Message.ToString, "Error")
                End Try
            End Sub