tags:

views:

1532

answers:

4

I populated a datagridview from a datatable. How do I read from the datagridview when the application is running?

+1  A: 

how did you populate it? is the DataSource something useful like a BindlingList? If it is then something like:

BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource;
//substitute your business object type for T 
T entity = bindingSource.Current as T;

would get you the entity bound to the row.

Otherwise there is always the datagridview.Columns[n].Cells[n].Value but really I'd look at using the objects in the DataSource

Edit: Ah... a datatable... righto:

 var table = dataGridView1.DataSource as DataTable;

 foreach(DataRow row in table.Rows)
 {
     foreach(DataColumn column in table.Columns)
     {
         Console.WriteLine(row[column]);
     }
 }
Hamish Smith
+1  A: 

You can iterate through your datagridview and retrieve each cell.

for(int i =0; i < DataGridView.Rows.Count; i++){
  DataGridView.Rows.Columns["columnName"].Text= "";
}

There is an example here.

jdecuyper
A: 

namespace WindowsFormsApplication2 { public partial class Form1 : Form { public static DataTable objDataTable = new DataTable("UpdateAddress");

    public Form1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = "c:\\";
        openFileDialog1.Filter = "csv files (*.csv)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((myStream = openFileDialog1.OpenFile()) != null)
                {
                    string fileName = openFileDialog1.FileName;

                    List<string> dataFile = new List<string>();
                    dataFile = ReadList(fileName);
                    foreach (string item in dataFile)
                    {
                        string[] temp = item.Split(',');
                        DataRow objDR = objDataTable.NewRow();
                        objDR["EmployeeID"] = temp[0].ToString();
                        objDR["Street"] = temp[1].ToString();
                        objDR["POBox"] = temp[2].ToString();
                        objDR["City"] = temp[3].ToString();
                        objDR["State"] = temp[4].ToString();
                        objDR["Zip"] = temp[5].ToString();
                        objDR["Country"] = temp[6].ToString();
                        objDataTable.Rows.Add(objDR);

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
    }

    public static List<string> ReadList(string filename)
    {
        List<string> fileData = new List<string>();
        StreamReader sr = new StreamReader(filename);
        while (!sr.EndOfStream)
            fileData.Add(sr.ReadLine());
        return fileData;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        objDataTable.Columns.Add("EmployeeID", typeof(int));
        objDataTable.Columns.Add("Street", typeof(string));
        objDataTable.Columns.Add("POBox", typeof(string));
        objDataTable.Columns.Add("City", typeof(string));
        objDataTable.Columns.Add("State", typeof(string));
        objDataTable.Columns.Add("Zip", typeof(string));
        objDataTable.Columns.Add("Country", typeof(string));
        objDataTable.Columns.Add("Status", typeof(string));

        dataGridView1.DataSource = objDataTable;
        dataGridView1.Refresh();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        // Displays a SaveFileDialog so the user can save the backup of AD address before the update
        // assigned to Button2.
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        saveFileDialog1.Filter = "BAK Files|*.BAK";
        saveFileDialog1.Title = "Save AD Backup";
        saveFileDialog1.ShowDialog();

        if (saveFileDialog1.FileName != "")
        {
            TextWriter fileOut = new StreamWriter(saveFileDialog1.FileName); 
            //This is where I want read from the datagridview the EmployeeID column and use it in my BackupAddress method.
        }

    }
Probably would have been better to edit the question rather than posting this as an answer.
Hamish Smith
A: 

You might want to take a look at DataTable.WriteXml, and it's brother DataTable.ReadXml. No fuss, no muss saving of a DataTable.

Mark Brackett