Tuesday, December 6, 2011

C# DataGridView Tutorial

Add a new DataGridView object to your form then..

To add new columns to hold our data..
dataGridView1.Columns.Add("id","ID");
dataGridView1.Columns.Add("fname","First Name");
dataGridView1.Columns.Add("lname","Last Name");
dataGridView1.Columns.Add("dob","DOB");
 You can add data simply by..
int i = dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = "0";
dataGridView1.Rows[i].Cells[1].Value = "John";
dataGridView1.Rows[i].Cells[2].Value = "Doe";
dataGridView1.Rows[i].Cells[3].Value = "12/14/82";

Loop through the data by..
try
{
    foreach (DataGridViewRow dr in dataGridView1.Rows)
    {
        MessageBox.Show(dr.Cells[0].Value.ToString());
    }
}
catch { };

Reading it from a file, comma separated..
if (!File.Exists("customers.txt"))
{
    MessageBox.Show("customers file not found");
    return;
}

StreamReader rdr = new StreamReader(@"customers.txt");
string[] lines = rdr.ReadToEnd().Split('\n');
foreach (string line in lines)
{
    string[] info = line.Split(',');

    int i = dataGridView1.Rows.Add();
    dataGridView1.Rows[i].Cells[0].Value = info[0];
    dataGridView1.Rows[i].Cells[1].Value = info[1];
    dataGridView1.Rows[i].Cells[2].Value = info[2];
    dataGridView1.Rows[i].Cells[3].Value = info[3];
}

No comments:

Post a Comment