0

Hi,

I have a dataGridView that is bound to dataset.I have created a add new button for DatagridView. my problem is the studentid that is a primary key column which is already defined in the table. I am struggling to autoincrement the datatable.please review the code below and let me know how to proceed this.

button_click has 

dr = ds.Tables[0].NewRow();

dr["firstname"] = "code";
dr["lastname"] = "sss";
dr["grade"] = 45;
dr["studentID"]=dt.PrimaryKey = new DataColumn[] { dt.Columns["studentID"] };//error

ds.Tables[0].Rows.Add(dr);

the error message is unable to cast object of type System.Data.DataColumn[] to type system.Iconvertible.

2
Contributors
1
Reply
4
Views
6 Years
Discussion Span
Last Post by __avd
0

Do not assign value to auto-incr column.

System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("SrNo", typeof(int));
            dt.Columns.Add("Name");

            dt.Columns["SrNo"].AutoIncrement = true;
            dt.Columns["SrNo"].AutoIncrementSeed = 1;
            dt.Columns["SrNo"].AutoIncrementSeed = 1;

            dt.PrimaryKey = new System.Data.DataColumn[] { dt.Columns["SrNo"] };


            System.Data.DataRow r = dt.NewRow();
            r["Name"] = "foo";
            dt.Rows.Add(r);

            r = dt.NewRow();
            r["Name"] = "bar";
            dt.Rows.Add(r);

            foreach (System.Data.DataRow r1 in dt.Rows)
                Console.WriteLine(r1[0] + " " + r1[1]);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.