0
我想從datagridview編輯我的數據庫記錄並從那裏保存。我需要聲明哪些屬性才能編輯數據網格?而button2是我的保存按鈕,我如何更新到數據庫?有人請幫助我謝謝!c#將datagridview中的數據保存到數據庫
{
//Get ID
string strTagIds = string.Empty;
//Connection to datebase
string c1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
OleDbConnection con = new OleDbConnection(c1);
}
private void button1_Click(object sender, EventArgs e)
{
//button1.Click += new EventHandler(dataGridView1_CellContentClick);
//Bind button
string txt = textBox1.Text;
string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
string strSqlStatement = string.Empty;
strSqlStatement = "SELECT * FROM jiahe WHERE [User] = '" + txt + "'";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSqlStatement, objConnection);
DataSet ds = new DataSet();
objAdapter.Fill(ds);
DataTable dt = ds.Tables[0];
dataGridView1.DataSource = dt.DefaultView;
try
{
if (dt.Rows.Count == 1)
{
string strLine = string.Empty;
string strUser = string.Empty;
foreach (DataRow dr in dt.Rows)
{
string strTags = dr["Tag ID"].ToString();
strUser = dr["User"].ToString();
string strAge = dr["Age"].ToString();
string strPhoneNumber = dr["Phone Number"].ToString();
// prepare command string
string selectString = @"SELECT Status FROM jiahe where [User] = '" + textBox1.Text + "'";
// 1. Instantiate a new command with command text only
OleDbCommand cmd = new OleDbCommand(selectString, objConnection);
// 2. Set the Connection property
cmd.Connection.Open();
// 3. Call ExecuteScalar to send command
string str = cmd.ExecuteScalar().ToString();
cmd.Connection.Close();
}
}
else
{
if (dt.Rows.Count == 0)
{
MessageBox.Show("Invalid input!");
}
}
}
catch (Exception)
{
MessageBox.Show("Error!");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, EventArgs e)
{
//dataGridView1.BeginEdit(true);
//MessageBox.Show("Hello");
}
private void button2_Click(object sender, EventArgs e)
{
}
你能給我看一個它應該如何流動的粗略例子嗎? –
看看這裏http://www.switchonthecode.com/tutorials/csharp-tutorial-binding-a-datagridview-to-a-database或這裏http://khanrahim.wordpress.com/2010/04/10/插入更新-刪除與 - datagridview的 - 控制 - 在-C-Windows的應用程序/ – Coder