Object can't be "InvalidCastException: The OleDbParameter" in catch - c#

I an trying to do a simple task of reading from one table "tab2" in a database->save to xml and then reload it into table "tab1" both have the same structure, I asked previously and received the following code as an answer.
I am having problems I am now getting the database filed ONCE per item but with a date time stamp I don't think its writing the XML from reading the database properly I am running it twice to get the schema and once for data.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.accdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
//Conn.Close();//severl times connection has been open
Conn.Open();
DataSet ds = new DataSet();
ds.ReadXml(#"c:\\temp\\tab2.xml");
OleDbCommand cmd = new OleDbCommand();
//OleDbCommand cmd1 = new OleDbCommand();
DataTable dtCSV = new DataTable();
dtCSV = ds.Tables[0];
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
//cmd1.Connection = Conn;
for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
{
//for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
//{
// //cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
//}
cmd.Parameters.Clear();
if (dtCSV.Columns.Count > 1)
{
//command.Parameters.Add(new OleDbParameter("#EMPID", Convert.Tostring(empsplitIt[1])));
//cmd.Parameters.Add(dtCSV.Rows[row][0]);
cmd.Parameters.Add(new OleDbParameter("#Field1", Convert.ToString(dtCSV.Rows[row][0])));
cmd.Parameters.Add(new OleDbParameter("#dtCSV", Convert.ToString(dtCSV.Rows[row][1])));
cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (? , ?)");
cmd.ExecuteNonQuery();
}
}
//Conn.Close();
}
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
string strSql = "Select * from Table1"; //only launch in main
richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";
try
{
OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\\temp\\names.mdb; Persist Security Info = False");
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "fname,sname");
// Extract data set to XML file
ds.WriteXml(#"c:\\temp\\tab2.xml", XmlWriteMode.WriteSchema);
ds.WriteXml(#"c:\\temp\\tab2.xml");
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
}
}
}
I find from my code that there is two different connection strings with in it when I putin the corect spelling correcting these it now fails on the line
dtCSV = ds.Tables[0];
with this
Error System.IndexOutOfRangeException: Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
at WindowsFormsApp8.Form1.button1_Click(Object sender, EventArgs e) in
Code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
//Conn.Close();//severl times connection has been open
Conn.Open();
DataSet ds = new DataSet();
ds.ReadXml(#"c:\\temp\\tabel2.xml");
OleDbCommand cmd = new OleDbCommand();
//OleDbCommand cmd1 = new OleDbCommand();
DataTable dtCSV = new DataTable("tabel1");
dtCSV = ds.Tables[0];
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
//cmd1.Connection = Conn;
for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
{
//for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
//{
// //cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
//}
cmd.Parameters.Clear();
if (dtCSV.Columns.Count > 1)
{
//command.Parameters.Add(new OleDbParameter("#EMPID", Convert.Tostring(empsplitIt[1])));
//cmd.Parameters.Add(dtCSV.Rows[row][0]);
cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[row][0])));
cmd.Parameters.Add(new OleDbParameter("#field2", Convert.ToString(dtCSV.Rows[row][1])));
cmd.CommandText = ("INSERT INTO tabel1 ( field1, field2) VALUES (? , ?)");
cmd.ExecuteNonQuery();
}
}
//Conn.Close();
}
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
string strSql = "Select * from tabel2"; //only launch in main
richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";
try
{
OleDbConnection con = new OleDbConnection(ConnString);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "fname,sname");
// Extract data set to XML file
ds.WriteXml(#"c:\\temp\\tabel2.xml", XmlWriteMode.WriteSchema);
ds.WriteXml(#"c:\ \temp\\tabel2.xml");
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
}
}
}

Related

C# multi valued combo box value to SQL Server database

private void filljobid()
{
try
{
string jobid = "";
int newjobid, oldjobid;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("SELECT MAX(job_id) FROM job", con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
jobid = reader[0].ToString();
}
oldjobid = int.Parse(jobid.ToString());
newjobid = oldjobid + 1;
jobidtextbox.Text = newjobid.ToString();
}
catch (Exception)
{
MessageBox.Show("Error while connecting");
}
}
private void fillcustomercombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT customer_id,(first_name + ' ' + last_name + ' - ' + contact) AS CUSTOMERNAME FROM customer", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
customeridcombobox.DataSource = ds.Tables[0];
customeridcombobox.DisplayMember = "CUSTOMERNAME";
customeridcombobox.ValueMember = "customer_id";
cmd.ExecuteReader();
con.Close();
// CODE FOR DISPLAYING multiple values in another way, but not sure how to retrieve data from this function
// for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
// {
// customeridcombobox.Items.Add(ds.Tables[0].Rows[i][0] + " - " + ds.Tables[0].Rows[i][1] + " " + ds.Tables[0].Rows[i][2]);
// }
}
private void filldepotcombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT depot_id,(branch_name + ' - ' + region_name + ' - ' + location) AS DEPOTNAME FROM depot", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
depotidcombobox.DataSource = ds.Tables[0];
depotidcombobox.DisplayMember = "DEPOTNAME";
depotidcombobox.ValueMember = "depot_id";
cmd.ExecuteReader();
con.Close();
}
private void filljobtypecombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT job_type FROM jobtype", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
jobtypecombobox.DisplayMember = "job_type";
jobtypecombobox.ValueMember = "job_type";
jobtypecombobox.DataSource = ds.Tables[0];
cmd.ExecuteReader();
con.Close();
}
private void loadingcomboboxesdata_Load(object sender, EventArgs e)
{
fillcustomercombox();
filljobid();
filldepotcombox();
filljobtypecombox();
}
private void addnewjobbutton_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMoversDB;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into job (start_location, end_location, depot_id, job_type, customer_id,) values ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "','" + depotidcombobox.Text + "','" + jobtypecombobox.Text + "','" + customeridcombobox.Text + "')";
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Added new job");
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
What I'm trying to achieve is basically take the users selected value which is displayed in the combo box which is valuemember and then insert it into the database. Right now I get the error when I try to insert the data into the database. When I do the combo box with a single value it works fine but it doesn't work when I do it with multiple values.
Could someone close this question. I managed to solve my own question. I dont know if this solution is considered good but here you go.
private void addnewjobbutton_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO job(start_location, end_location, depot_id, job_type, customer_id) VALUES ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "',#3,#4, #5)"))
{
cmd.Connection = con;
//cmd.Parameters.AddWithValue("#1", startlocationtxtbox.SelectedText);
//cmd.Parameters.AddWithValue("#2", endlocationtxtbox.SelectedText);
cmd.Parameters.AddWithValue("#3", depotidcombobox.SelectedValue);
cmd.Parameters.AddWithValue("#4", jobtypecombobox.SelectedValue);
cmd.Parameters.AddWithValue("#5",customeridcombobox.SelectedValue);
con.Open();
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
}

retrieve the data using monthcalendar control

private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\\Users\\JAY\\Desktop\\Employee.mdb");
OleDbCommand cmd = new OleDbCommand("select * from Emp_Details WHERE DOB="+ monthCalendar1.SelectionRange.Start.ToShortDateString() +"", con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Emp_Details");
txtEmployeeNo.Text = ds.Tables[0].Rows[0][0].ToString();
txtName.Text = ds.Tables[0].Rows[0][1].ToString();
txtAddress.Text = ds.Tables[0].Rows[0][2].ToString();
comboBox1.Text = ds.Tables[0].Rows[0][3].ToString();
txtMobNo.Text = ds.Tables[0].Rows[0][4].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Basically i want to retrieve the data through monthcaledar control...but
when i click to date of monthcalendar control i got exception there is no row at position 0
Don't use inline parameters, you can use Parameterized query as below
using (var con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\Users\JAY\Desktop\Employee.mdb"))
using (var cmd = new OleDbCommand("select * from Emp_Details WHERE DOB= ?", con))
{
cmd.Parameters.AddWithValue("#P1", monthCalendar1.SelectionRange.Start);
using (var da = new OleDbDataAdapter(cmd))
{
da.Fill(ds, "Emp_Details");
if (ds.Tables["Emp_Details"] !=null && ds.Tables["Emp_Details"].Rows.Count>0)
{
DataRow dr = ds.Tables["Emp_Details"].Rows[0];
txtEmployeeNo.Text = dr[0].ToString();
txtName.Text = dr[1].ToString();
txtAddress.Text = dr[2].ToString();
comboBox1.Text = dr[3].ToString();
txtMobNo.Text = dr[4].ToString();
}
}
}

Unable to compare the columns in SqlBulkCopy

Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
//matching columns
//SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
//SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
I know I need to add something like:
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
but I am not sure where I am supposed to add it in the above code
The column mappings are to be added to the bulkCopy.ColumnsMappings collection:
var mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
bulkCopy.ColumnMappings.Add(mapping1);
You do the mapping before you execute the WriteToServer call.
The MSDN documentation of SqlBulkCopyColumnMapping has further documentation and an example.

Error with SqlBulkCopyColumnMapping

I am able to import excel sheet data into sql server table but i am unable to implement column mapping. please help.
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
bulkCopy.WriteToServer(dr);
con.Open();
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
con.Close();
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try { SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
Error:
No value given for one or more required parameters.
You created but didn't add the mappings to SqlBulkCopy.
Add the code below:
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);

How To AutoNumber With in Database?

I use C# Windows Form. i'm need auto number not duplicate.
I'm Import file excel to datagridview and Generate field 'id' for not duplicate.
But don't work.
Ex.
First Import.
ID | Name
P001 => Auto Gen | A
P002 => Auto Gen | B
Second Import.
ID | Name
P001 => Auto Gen But I need P003 | C
P002 => Auto Gen But I need P004 | D
Code:
SqlConnection Conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
StringBuilder sb = new StringBuilder();
SqlTransaction tr;
private void testExcel_Load(object sender, EventArgs e)
{
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
TextBox1.Text = openFileDialog1.FileName;
File.ReadAllText(TextBox1.Text);
}
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + TextBox1.Text + #";Extended Properties=""Excel 8.0; HDR=Yes; IMEX=1; ImportMixedTypes=Text; TypeGuessRows=0"" ";
OleDbCommand cmd = new OleDbCommand("SELECT * " + "FROM [SHEET1$]", conn);
DataSet ds = new DataSet();
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
ad.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception)
{
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
tr = Conn.BeginTransaction();
sb.Remove(0, sb.Length);
sb.Append("INSERT INTO tbl_Asset (AsId,AsName)");
sb.Append("VALUES (#Asid,#AsName)");
string sqlSave = sb.ToString();
cmd.CommandText = sqlSave;
cmd.CommandType = CommandType.Text;
cmd.Connection = Conn;
cmd.Transaction = tr;
cmd.Parameters.Clear();
cmd.Parameters.Add("#Asid", SqlDbType.VarChar).Value = dataGridView1.Rows[i].Cells[0].Value;
cmd.Parameters.Add("#AsName", SqlDbType.VarChar).Value = dataGridView1.Rows[i].Cells[1].Value;
cmd.ExecuteNonQuery();
tr.Commit();
}
MessageBox.Show("Insert Done", "Result", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void button3_Click(object sender, EventArgs e)
{
int cellnum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
cellnum = cellnum + 1;
dataGridView1.Rows[i].Cells[0].Value = txtID.Text + "000" + cellnum;
}
}
Thanks you so much for you time. :)
If you're doing this purely in SQL Server, you could add an identity column then add a computed column to give you your custom format:
alter table MyTable add MyNewColumn as 'P' + right('000' + cast(MyIdentColumn as varchar(3)), 3)
Note that this example will give unexpected results after your identity reaches 1000.

Categories