How to access DetailsView's fields programmatically

To display data in a DetailsView control, we use BoundField elements or TemplateField elements. This example demonstrates how to access field's values of a DetailsView control programmatically, when we have created DetailsView control using BoundField elements.

When a DetailsView control displays data, each row corresponds to a BoundField. We know that the DetailsView control renders each field of a record as a table row.

The Rows[0] indicates the first field and Rows[1] indicates the second field and DetailsView renders a cell with a textbox in it.

<asp:DetailsView ID="DetailsView1" runat="server"   
   AllowPaging="true" DataKeyNames="Code" 
   DataSourceID="MyDataSource"    AutoGenerateRows="false" 
     OnDataBound="DetailsView1_DataBound"
   AutoGenerateInsertButton="true" 
   
   AutoGenerateEditButton="true">
   <Fields>
   
   <asp:BoundField  DataField="Name" HeaderText="Name" />
   <asp:BoundField  DataField="description" HeaderText="description" />
   
   </Fields>
   
   </asp:DetailsView>
<asp:SqlDataSource ID="MyDataSource"  
ConnectionString="<%$Connectionstrings:ERPConnectionString%>"
SelectCommand="SELECT * FROM Sample" 
UpdateCommand="Update SAMPLE SET Name=@Name,description=@description Where Code=@Code"
DeleteCommand="Delete SAMPLE Where Code=@Code" 
InsertCommand="Insert SAMPLE(Code,Name,description) VALUES(@Code,@Name,@description)"
runat="server"/>


output of DetailsView control

The following code example demonstrates how to use the DataBound event handler to access programmatically the bound fields in a DetailsView control. The below code works only when DetailsView control uses the BoundField element. We cannot apply the same logic when we are using Template fields.

protected void DetailsView1_DataBound(object sender, EventArgs e)
{
    string description=DetailsView1.Rows[1].Cells[1].Text;
}


DetailsView Articles
Most Viewed