Saturday 26 May 2012

displaying data in detailsview

       There is difference between grid view and details view where details view represents only single data.
e.g. If roll number of student to be entered in text box, detail view should display all related information about that student only.
        Here I am sharing that, how to display specific record from database to details view. Hope it would be helpful for you.
        Make an adjustment as per your database connection..


1) Designer Code:

 <asp:Label ID="Label1" runat="server" Text="Enter Merit No"></asp:Label>

    <asp:TextBox ID="txtMerit" runat="server" Width="71px"></asp:TextBox>
   

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="OK"
        Width="65px" Font-Bold="True" />
 

    <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"
        CellPadding="4" ForeColor="Black" BackColor="#CCCCCC"
    BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellSpacing="2">

        <FooterStyle BackColor="#CCCCCC" />
        <RowStyle BackColor="White" />
        <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />

    </asp:DetailsView>

2) On Display Button Code:

protected void btnDisplayData_Click(object sender, EventArgs e)
        {
            OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;
            Data Source=StudentDatabase1.mdb;Persist Security Info=True;");

            string strSql = "Select * From [student_merit_record] Where [merit no]='" + txtMerit.Text + "'";
            OleDbCommand cmd = new OleDbCommand(strSql);
            cmd.CommandText = strSql;
            cmd.Connection = con;
            con.Open();
            OleDbDataAdapter da = new OleDbDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds, "student_merit_record");
            DetailsView1.Visible = true;
            DetailsView1.DataSource = ds.Tables["student_merit_record"];
            DetailsView1.DataBind();
            con.Close();
        }