DataGrid not displaying data

2.9k views Asked by At

I am trying to display a DataGrid on my mobile application after reading a CSV file and processing it. Here is what I have so far:

private void btOpenFile_Click(object sender, EventArgs e)
{
    try 
    {           
        // Process all data into an array of Object 
        // this.records array contains objects of type MyRecord

        // Create datatable and define columns
        DataTable dt = new DataTable("myDt");
        dt.Columns.Add( new DataColumn("String A",typeof(string)));
        dt.Columns.Add( new DataColumn("Int 1", typeof(int)));                   

        // Loop through and create rows
        foreach(MyRecord record in records) {
            DataRow row = dt.NewRow();                        
            row[0] = record.stringA;
            row[1] = record.int1;
            dt.Rows.Add(row);
        }   

        // Create dataset and assign it to the datasource..
        DataSet ds = new DataSet("myDs");
        ds.Tables.Add(dt);                                          
        dataGrid.DataSource = ds;
        dataGrid.Refresh();

    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: " + ex.Message,"Error");
    }
}

All I get is a blank data grid component when running my application. Can somebody point out my mistake? or how to do this correctly?

6

There are 6 answers

1
PaulSh On BEST ANSWER

Try without DataSet dataGrid.DataSource = dt;

0
RobH On

Instead of:

dataGrid.DataSource = ds;         
dataGrid.Refresh(); 

Try:

dataGrid.SetDataBinding(ds, "myDt");

This has the effect of setting the datasource and datamember at the same time.

0
AudioBubble On

Try this it would help...

DataSet Ds = new DataSet();
DataTable Dt = new DataTable();

Ds.Tables.Add(Dt);
Dt.Columns.Add(new DataColumn("String A", typeof(string)));                
Dt.Columns.Add(new DataColumn("Int 1", typeof(int)));      

Dt.Rows.Add(new object[] { "Patricia", 3 });
Dt.Rows.Add(new object[] { "John", 4 });
Dt.Rows.Add(new object[] { "Mayer", 5 });
0
AudioBubble On

The problem is You cannot refer the datasource to only as Dataset it should be something like Dataset.Datatable... Here it is an example

Dataset DS = new Dataset();
DS.Tables.Add(TableName);

//
Populate dataset
//

mydatagrid.Datasource = DS.Tables[0];

So in short you have to refer to the table within the dataset to display the Data... Hope this Helps... :)

0
Johanvw On

It should work as well if you set the DataSource to the table inside the DataSet as well .. something like:

datagrid.DataSource = ds.Tables["myDt"];

Remember that a dataset could contain more than one table and we have to tell it explicitly which one to use or where to look :)

hth

0
Uma On

I know its very late to answer....But it will be helpful to others...

DataSet ds = gridUpdate.GridUpdate();

(dont worry about gridUpdate.GridUpdate()its my function to Create dataset)

dataGridView1.DataSource = ds.Tables[0]