主题:C# DataGrid 数据录入问题
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection("server=.;uid=sa;pwd=;database=Book");
sda = new SqlDataAdapter("select * from BookInfo",conn);
sda.Fill(ds, "BookInfo");
this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
if (ds.Tables["BookInfo"].Rows.Count == 0)
{
this.btnUpdate.Enabled = false;
this.btnDel.Enabled = false;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
string insCmd = "Insert into BookInfo values(@BookName,@BookAuthor,@BookPrice)";
//初始化InsertCommand
sda.InsertCommand = new SqlCommand(insCmd, conn);
//声明参数并制定数据库的列和版本
param = sda.InsertCommand.Parameters.Add("@BookName", SqlDbType.VarChar);
param.SourceColumn = "BookName";
param.SourceVersion = DataRowVersion.Current;
param = sda.InsertCommand.Parameters.Add("@BookAuthor", SqlDbType.VarChar);
param.SourceColumn = "BookAuthor";
param.SourceVersion = DataRowVersion.Current;
param = sda.InsertCommand.Parameters.Add("@BookPrice", SqlDbType.Decimal);
param.SourceColumn = "BookPrice";
param.SourceVersion = DataRowVersion.Current;
//如果数据集已更改,则插入记录
if (ds.HasChanges())
{
try
{
//DataAdapter 的 Update() 方法将调用 InsertCommand
sda.Update(ds, "BookInfo");
MessageBox.Show("信息已插入");
this.btnUpdate.Enabled = true;
this.btnDel.Enabled = true;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("提供详细信息以添加新记录");
}
信息始终不能成功录入 最终显示"提供详细信息添加" 代码能编译成功
请高手指点一下
{
conn = new SqlConnection("server=.;uid=sa;pwd=;database=Book");
sda = new SqlDataAdapter("select * from BookInfo",conn);
sda.Fill(ds, "BookInfo");
this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
if (ds.Tables["BookInfo"].Rows.Count == 0)
{
this.btnUpdate.Enabled = false;
this.btnDel.Enabled = false;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
string insCmd = "Insert into BookInfo values(@BookName,@BookAuthor,@BookPrice)";
//初始化InsertCommand
sda.InsertCommand = new SqlCommand(insCmd, conn);
//声明参数并制定数据库的列和版本
param = sda.InsertCommand.Parameters.Add("@BookName", SqlDbType.VarChar);
param.SourceColumn = "BookName";
param.SourceVersion = DataRowVersion.Current;
param = sda.InsertCommand.Parameters.Add("@BookAuthor", SqlDbType.VarChar);
param.SourceColumn = "BookAuthor";
param.SourceVersion = DataRowVersion.Current;
param = sda.InsertCommand.Parameters.Add("@BookPrice", SqlDbType.Decimal);
param.SourceColumn = "BookPrice";
param.SourceVersion = DataRowVersion.Current;
//如果数据集已更改,则插入记录
if (ds.HasChanges())
{
try
{
//DataAdapter 的 Update() 方法将调用 InsertCommand
sda.Update(ds, "BookInfo");
MessageBox.Show("信息已插入");
this.btnUpdate.Enabled = true;
this.btnDel.Enabled = true;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("提供详细信息以添加新记录");
}
信息始终不能成功录入 最终显示"提供详细信息添加" 代码能编译成功
请高手指点一下