Hey guys,

I am trying to write down a code for generating 'ID' automatically
and then store it in table. There some errors, i couldn't rectify.

This is my code :

int ctr = 1;
            int len;

            DataTable dt = new DataTable();
            DataRow dr;
            DataSet ds = new DataSet();

            string code;
            string cde;

            dt = dB1DataSet1.Tables["TT"];
            len = dt.Rows.Count - 1;  //Error : did not declare object instance.

            dr = dt.Rows[len];
            code = dr["ID"].ToString();
            cde = code.Substring(1,3); //Error : Start index cannot be greater than length of the string.

            ctr = Convert.ToInt32(cde);

            if ((ctr <=1) && (ctr < 9))
            {
                ctr = ctr + 1;

                
                textBox1.Text = "C00" + ctr;


               
            }
            else if ((ctr >= 9) && (ctr < 99))
            {
                ctr = ctr + 1;
                textBox1.Text = "C0" + ctr;
            }
            else if (ctr >= 99)
            {
                ctr = ctr + 1;
                textBox1.Text = "C" + ctr;
            }

             string qery = "insert into TT values('" + textBox1.Text + "' , '" + textBox4.Text + "')";
                OleDbCommand cmd2 = new OleDbCommand(qery, olcon);

                cmd2.ExecuteNonQuery();

                MessageBox.Show("Company Saved successfully");



                olcon.Close();
            
        }

Help me to know the reason for these errors. And also if you can suggest alternate code.
that would be great.


Regards
Ajinkya

Don't know what dB1DataSet1.Tables["TT"] is but that table probably contains no rows.
The string code is empty or null, so SubString complains it cannot index it.

Here 'TT' refers to as table name.
And i also inserted a row and then
tried generating 'ID'. But it didn't
work. Do you have any other way?

Thanks

You create a dataset then try to retrieve a table from it, but you haven't loaded anything into the dataset. You then try to get a row from the non-existent table, then data from the non-existent row.

You should read this.

You create a dataset then try to retrieve a table from it, but you haven't loaded anything into the dataset. You then try to get a row from the non-existent table, then data from the non-existent row.

You should read this.

This article has been dead for over six months. Start a new discussion instead.