المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Newly added rows from Datagrid



C# Programming
10-23-2011, 01:40 PM
Hi

For my assignment, I need to find out all rows that were newly added into the datagrid and add it to the database.

I have pasted my code below, getting error in setting dRow where it says index is out of range.. I thought the newly added row can be accessed thru the index. Please let me know how to access the cells in newly added row.

public partial class AllCustomer : Form { private int ii; public AllCustomer() { InitializeComponent(); string strConnection = "Data Source=.;Initial Catalog=Company;Integrated Security=True"; SqlConnection sqlconn = new SqlConnection(strConnection); DataSet ds = new DataSet(); string sqls = "select * from CustomerMaster"; SqlDataAdapter da = new SqlDataAdapter(sqls, sqlconn); sqlconn.Open(); da.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; ii = dataGridView1.RowCount; sqlconn.Close(); } private void btn_Add_Click(object sender, EventArgs e) { string strConnection = "Data Source=.;Initial Catalog=Company;Integrated Security=True"; SqlConnection sqlconn = new SqlConnection(strConnection); DataSet ds = new DataSet(); string sqls = "select * from CustomerMaster"; SqlDataAdapter da = new SqlDataAdapter(sqls, sqlconn); SqlCommandBuilder cmdBldr = new SqlCommandBuilder(da); sqlconn.Open(); da.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; for (int j = ii; j >= dataGridView1.RowCount; j++) { DataRow dRow = ds.Tables[0].NewRow(); dRow["cust_name"] = dataGridView1.Rows[j].Cells["cust_name"].Value.ToString(); dRow["cust_st_addr"] = dataGridView1.Rows[j].Cells["cust_st_addr"].Value.ToString(); dRow["cust_city_state_zip"] = dataGridView1.Rows[j].Cells["cust_city_state_zip"].Value.ToString(); dRow["cust_phone"] = dataGridView1.Rows[j].Cells["cust_phone"].Value.ToString(); dRow["cust_stat_cd"] = dataGridView1.Rows[j].Cells["cust_stat_cd"].Value.ToString(); //datetime hard coded for test only... dRow["cust_add_dt"] = "2011-10-14"; dRow["cust_updt_dt"] = "2011-10-15"; ds.Tables[0].Rows.Add(dRow); } da.Update(ds.Tables[0]); } }