Hi. I am doing a C# windows form application and I am retrieving data from a database and saving in a datatable temporarily. I have to access each cell and update them.

try
            {
                string TaskStatus = "Assigned";
                SqlCommand cmd1 = new SqlCommand("SELECT Day_Date FROM tblDaily_Task_Schedule WHERE Task_Status='" + TaskStatus + "'", con);

                SqlDataAdapter myadap = new SqlDataAdapter(cmd1);
                DataSet myds = new DataSet();
                DataTable mytable = new DataTable("tblDaily_Task_Schedule");
                myds.Tables.Add(mytable);
                myadap.Fill(mytable);
                string eff = (cmd1.ExecuteScalar()).ToString();

                dataGridView1.DataSource = myds;
                dataGridView1.DataMember = "tblDaily_Task_Schedule";

                for (int i = 0; i < mytable.Columns.Count; i++)
                {
                    for (int j = 0; j < mytable.Rows.Count; j++)
                    {
                        DateTime dt1 = Convert.ToDateTime(dataGridView1.Rows[j].Cells[j].Value);
                       
                        DateTime dt2 = dt1.AddDays(1);
                        DateTime dt3 = DateTime.Now;

                        if (dt3 > dt2)
                        {
                            string sta = "Pending";
                            SqlCommand cmd3 = new SqlCommand("UPDATE tblDaily_Task_Schedule SET Task_Status='" + sta + "'", con);
                            cmd3.ExecuteNonQuery();
                        }
}

My problem is that how do I check each row? how do i modify the 2nd for loop (for (int j = 0; j < mytable.Rows.Count; j++))?

AND also how do i change the UPDATE command to be able to update at that particular ros in the database.

Recommended Answers

All 2 Replies

Hi, if you have dgv bound to dataTable you can only loop through the dataTable, and retreive all the data from dataTable (no need from dgv), because all the data put into dgv, are "automatically" saved into dataTable as well (because of the binding source).

1st loop has to go by looping through the rows, and 2nd one has to loop through the columns:

for (int i = 0; i < table.Rows.Count; i++)
            {
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    DateTime dt1 = Convert.ToDateTime(table.Rows[i][j]).AddDays(1);
                    if (DateTime.Now > dt1)
                    {
                        string sta = "Pending";
                        SqlCommand cmd3 = new SqlCommand("UPDATE tblDaily_Task_Schedule SET Task_Status = '" + sta + "'", con);
                        cmd3.ExecuteNonQuery();
                    }
                }
            }

Thanks a lot!!! it worked!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.