c# ado.net 的使用 产生了一点问题 求大神指点
在from1添加了一个dataGridView 和两个button
我想实现的是button1 加载数据 然后对加载的数据 进行修改后 点击button2 修改的数据进入数据库保存
但是运行时 加载没问题 点击修改 抛出异常说“对于不返回任何键列值的selectcommand,不支持updatecommand动态sql生成 ” 这个怎么弄啊
以下是源代码
SqlConnection conn;
SqlDataAdapter adapter;
private void button1_Click(object sender, EventArgs e)//加载数据
{
conn = new SqlConnection("Data Source=O8RS63RAGSIE4AR;Initial Catalog=MyDB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("select * from student", conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
dataGridView1.Columns[i].Width = 84;
}
button1.Enabled = false;
dataGridView1.Columns[0].ReadOnly = true;
}
private DataTable dbcoon(string strSql)
{
conn.Open();
this.adapter = new SqlDataAdapter(strSql, conn);
DataTable dtSelect = new DataTable();
int rnt = this.adapter.Fill(dtSelect);
conn.Close();
return dtSelect;
}
private void button2_Click(object sender, EventArgs e)//修改数据
{
if (dbUpdate())
{
MessageBox.Show("修改成功!");
}
}
private Boolean dbUpdate()
{
string strSql = "select * from student";
DataTable dtUpdate = new DataTable();
dtUpdate = this.dbcoon(strSql);
dtUpdate.Rows.Clear();
DataTable dtShow = new DataTable();
dtShow = (DataTable)this.dataGridView1.DataSource;
for (int i = 0; i < dtShow.Rows.Count; i++)
{
dtUpdate.ImportRow(dtShow.Rows[i]);
}
try
{
this.conn.Open();
SqlCommandBuilder CommandBuilder = new SqlCommandBuilder(this.adapter);
this.adapter.Update(dtUpdate);
this.conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return false;
}
dtUpdate.AcceptChanges();
return true;
}
}
[解决办法]
1. 查看数据库表中是否存在主键,没有主键,修改表的定义,定义一个主键;
2. 查看程序中自定义数据集是否存在主键,如果不存在添加主键。
dataset定义主键:
代码显示了如何为 DataSet 的 EmployeesList 表设置主键:
c#
DataColumn[] keys = new DataColumn[1];
keys[0] = m_oDS.Tables["EmployeesList"].Columns["EmployeeID"];
m_oDS.Tables["EmployeesList"].PrimaryKey = keys;