Thursday, 5 February 2015

How to show the record using DetailsView in ASP.NET


How to show the record using DetailsView in ASP.NET


To show complete details about a record, we can use DetailsView control


In the  .aspx page we have a DetailsView control of ASP .Net  with AutoGenerateColumns true and other with false. The first DetailsView displays all the default columns from the datasource automatically and 2nd one let us define our structure and style of the data to display.

<asp:DetailsView ID="DetailsVw1" runat="server" AutoGenerateRows="true" />



 <hr />DetailsView with custom Value
        <asp:DetailsView ID="DetailsVw2" runat="server" AutoGenerateRows="false">
            <Fields>                
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="Father Name" DataField="FatherName" />
                <asp:BoundField HeaderText="Age" DataField="Age" />
                <asp:BoundField HeaderText="Mobile" DataField="Mobile" />
            </Fields>
        </asp:DetailsView>

In the .CS code, I have used ADO.NET to Get the data from the database and specified the data source to the DetailsView control.
string Connectionstr= ConfigurationManager.ConnectionStrings["Manishconnection"].ConnectionString;
 protected void Page_Load(object sender, EventArgs e)
 {

if (!IsPostBack)
 {
  FillData();
  }
 }
private void FillData()
  {
   DataTable dt= new DataTable();

  // get the connection

 using (SqlConnection con = new SqlConnection(Connectionstr))
  {
  // write the sql statement to execute
    string sql = "SELECT AutoId, Name, FatherName, Age, mobile FROM
    ManishDetail ORDER By Id";
    // instantiate the command object to fire
  using (SqlCommand cmd = new SqlCommand(sql, con))
     { 
        // get the adapter object and attach the command object to it
       using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
        {
  // fire Fill method to fetch the data and fill into DataTable
        ad.Fill(dt);
        }
       }
    }

 // specify the data source for the DetailsView

 DetailsVw1.DataSource = dt;// bind the data now

    DetailsVw1.DataBind(); DetailsVw2.DataSource = dt; DetailsVw2.DataBind();
    }




We have kept AutoGeneratedRows property of the first DetailsView to true (by default it has true value) so several rows corresponding to each columns of the data source will be created. The 2nd DetailsView takes of the fields specified with their header and footer specified in the asp:BoundField and asp:TemplateField and displays the record.

No comments:

Post a Comment

Working with 3- Tier Architecture in C#

  Introduction In this article we will learn Use to 3- Tier architecture in C#.NET application. 3-Tier architecture is very famous and ...