Rockstar
Rockstar

Reputation: 25

Displaying rows dynamically

i want to show all the records which are in ms access database,but it displays only one record... I have the following code

private void Form1_Load(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
        con.Open();
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        string sql = "SELECT * From tblCompany";

        da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
        da.Fill(ds);
        DataRow dr = ds.Tables[0].Rows[0];
        int cnt = ds.Tables[0].Rows.Count;
        textBox1.Text = cnt.ToString();
        for (int i = 0; i < cnt; i++)
        {
            dataGridView1.Rows[i].Cells[0].Value = dr.ItemArray.GetValue(1).ToString();
            dataGridView1.Rows[i].Cells[1].Value = dr.ItemArray.GetValue(2).ToString();
        }


    }

how can i display all the records from the ms access database,in my DataGridView?

Upvotes: 0

Views: 1702

Answers (2)

Stecya
Stecya

Reputation: 23266

dataGridView1.Rows.Add(cnt);
for (int i = 0; i < cnt; i++)
{
    DataRow row = ds.Tables[0].Rows[i];
    dataGridView1.Rows[i].Cells[0].Value = row.ItemArray.GetValue(0).ToString();
    dataGridView1.Rows[i].Cells[1].Value = row.ItemArray.GetValue(1).ToString();
}

Upvotes: 3

Petko Petkov
Petko Petkov

Reputation: 750

If you want to access rows and columns in the gridview directly, you have to create them

 dataGridView1.Columns.Add("c1", "c1");
 dataGridView1.Columns.Add("c2", "c2");
 dataGridView1.Rows.Add(10);

will add 10 empty rows with 2 columns in the grid, then you can fill them in with values.

Alternativly you can bind your dataset to the control

 dataGridView1.DataSource = ds.Tables[0]

will display your table with autogenerated columns , without having to setup the gridview.

Upvotes: 2

Related Questions