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.

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]);
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.