You must Sign In to post a response.
  • Category: ASP.NET

    Displaying the database record using datatable in using c#

    i am displaying the database record using datatable
    In LatestNewsMaster table record as follows

    id Subject Link Active
    1 Defect Mail defectmail.aspx A
    2 Accounts Fee accountsfee.aspx A
    3 Latestenews page Latestnews.aspx A

    My code as follows

    string constr = ConfigurationManager.ConnectionStrings["Reception2_DB"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    using (SqlCommand cmd = new SqlCommand("select Link from LatestNewsMaster where active <> 'd'"))
    cmd.Connection = con;
    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
    DataTable dt = new DataTable();
    label1.Text = dt.Rows[0][0].ToString().Trim();
    return dt;

    But when i run in label dsiplaying only firt recrod defectmail.aspx in the label1. not displaying all the three link records from the database.

    from my above code what is the mistake i made.
  • #763693
    Hai Rao,
    The below code is not correct:

    label1.Text = dt.Rows[0][0].ToString().Trim();

    You need to modify it like:

    for(int i=0; i< dt.Rows.Count; i++)
    lable1.Text += dt.Rows[i][0].ToString().Trim() + "\n";

    Hope it will be helpful to you.

    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)

  • #763694
    Yes, it should return only first record as per your code because you are calling 0th index record only as per your code, see the below piece of code.

    label1.Text = dt.Rows[0][0].ToString().Trim();

    In above code dt.Rows you are calling 0th index only, if you want to retrieve all the records available in table then you need to iterate the loop and then concatenate and assign back to your control.

    Refer below sample code to achieve that

    for(int i=0;i<dt.Rows.Count;i++)
    label1.Text = label1.Text +dt.Rows[i]["ColumnName"].ToString() + " , ";

    In above code instead of ColumnName you can provide the index of the column also, and instead of ", " separator you can use whatever you want.

    Hope this will helpful to you...

    Give respect to your work, Instead of trying to impress your boss.

    Blog :

  • #763697
    If you want to display more than one record you have to use, GridView, DataList, or Repeator control.

    You can just assign the data source and bind it. This is the correct way.

    In case if you want to bind in the Lable you an use the for loop and assign the test

    for(int i=0; i< dt.Rows.Count; i++)
    lable1.Text += dt.Rows[i][0].ToString().Trim() + "\n";

    By Nathan
    Direction is important than speed

  • #763858
    Use gridview for that case. Look here
    If you are unable to do something properly for the first time, call it Version 1.0!

    Thanks & Regards,

Sign In to post your comments