本文介绍了如何将表名作为参数传递给使用Gridview更新数据库中的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨朋友
Hi Friends
I have Multiple Tables in my Access Database. And I want to Update a Particular Table through passing a parameter for table name in Gridview.
For Example if i want to update a table with name of Satya. i will type satya in textbox nd click on Search button particular table is updating to gridview. now i want to update the same table.
I tried my code as below.
private void btnSaveGrid_Click(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Administrator\Documents\Database3.accdb"))
{
conn.Open();
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
string tabl1 = textBox1.Text.ToString();
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO tabl1 (EmpName, Sname) VALUES(@EmpName,@Sname)", conn))
{
cmd.Parameters.AddWithValue("@EmpName", row.Cells[1].Value);
cmd.Parameters.AddWithValue("@Sname", row.Cells[2].Value);
cmd.ExecuteNonQuery();
MessageBox.Show("success");
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
conn.Close();
}
// below table Search Code is working good.
private void btnSearch_Click(object sender, EventArgs e)
{
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Administrator\Documents\Database3.accdb";
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
String query = String.Format("Select * from {0}", textBox1.Text);
cmd.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
推荐答案
string queary = String.Format("INSERT INTO {0} (EmpName, Sname) VALUES (@EmpName, @Sname)", tabl1);
private void btnSaveGrid_Click(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Administrator\Documents\Database3.accdb"))
{
conn.Open();
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
string tabl1 = textBox1.Text.ToString();
string queary = String.Format("INSERT INTO {0} (EmpName, Sname) VALUES (@EmpName, @Sname)", tabl1);
using (OleDbCommand cmd = new OleDbCommand(queary, conn))
{
cmd.Parameters.AddWithValue("@EmpName", row.Cells[1].Value);
cmd.Parameters.AddWithValue("@Sname", row.Cells[2].Value);
cmd.ExecuteNonQuery();
MessageBox.Show("success");
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
conn.Close();
}
}
这篇关于如何将表名作为参数传递给使用Gridview更新数据库中的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!