How to Bind DataTable Column to DataGridView Column

In ASP.NET 3.0, WIndows form app I am trying to bind DataGridView columns to DataTable columns as follows:

dsLine = sqlClass.getDataSet(strSQL, "dsLine");
dtLine = dsLine.Tables[0];

dgv.Columns[0].DataPropertyName = dtLine.Columns["descr"].ToString ();
dgv.Columns[1].DataPropertyName = dtLine.Columns["quantity"].ToString();
dgv.Columns[2].DataPropertyName = dtLine.Columns["unitprc"].ToString();

On executing the lines above the program does not error out but the columns in the DataGridView are blank. What is the correct way to do this

Many thanks,
Mike Thomas





Answer this question

How to Bind DataTable Column to DataGridView Column

  • Sylvia msdn forum

    Many thanks for your reply. I got the situation to work with the code below. I am not yet sure what the downside would be to doing it this way.


    strSQL = "Select * from invcustl where ihpk = " +
    dsHead.Tables[0].Rows[0]["ihpk"].ToString() +
    " order by ilpk ";

    dsLine = sqlClass.getDataSet(strSQL, "dsLine");
    dtLine = dsLine.Tables[0];

    Int32 intI = 0;
    foreach ( DataRow row in dtLine.Rows )
    {

    dgv.Rows.Add(dtLine.Rows[intI]["descr"],
    dtLine.Rows[intI]["quantity"],
    dtLine.Rows[intI]["unitprc"]);

    intI = intI + 1;
    }

    Mike Thomas

  • Daniel Adeniji

    If you want to add data in a dgv, you should add new rows. Columns is used to define the dgv's format while the data are stored in dgv.Rows(the same as DataTable class). Of course, before you add rows into dgv you should add columns in advance.

    BTW, I suggest you use the designer to generate code automatically.



  • RayCan

    ive got this working fine for typed dataset.

    Private Sub CreateColumns()

    For i As Integer = 0 To Me.CostingDataSet1.Bill_AmountTypes.Rows.Count - 1

    Dim columnname As String = Me.CostingDataSet1.Bill_AmountTypes(i).AmountType.Trim

    Me.Dgv1.Columns.Add(columnname, columnname)

    Me.Dgv1.Columns(columnname).DataPropertyName = columnname

    Next

    End Sub

     

    now i see u are harcoding the line dtLine.Columns["descr"].ToString (); 

    whereby u could directly go 

    dgv.Columns[0].DataPropertyName = "descr"       

    which is lesser desirable,   but are you sure you are giving the right property name by doing this:

    dtLine.Columns["descr"].ToString (); 

    i used this somewhere:  me.tb.Columns("descr").ColumnName  and it works. i dont know about asp , .

    you should just verify whatdtLine.Columns["descr"].ToString () is returning, i perhaps think it is not right, if not the problem is something else.,

     



  • How to Bind DataTable Column to DataGridView Column