我想从datagridview编辑我的数据库记录并从那里保存。我需要声明哪些属性才能使我编辑数据网格?而button2是我的保存按钮,我该如何更新到数据库?有人请帮助我谢谢!
{
//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)
{
}
答案 0 :(得分:0)
您需要更改datagridview单元格内容值。您应该创建一个字符串,每次使用所选行的ID /索引编辑行时都会更新该字符串。然后,您可以在单击button2时对数据库进行更新。