这是我的代码:
public partial class Form1 : Form
{
SqlCommandBuilder cmbl;
string con = "Data Source=localhost;Initial Catalog=db;Persist Security Info=True;User ID=sa;Password=1234";
SqlDataAdapter sdaHFP;
string QueryDgvHFP = "SELECT * FROM HFP";
DataTable dtHFP;
SqlConnection cn;
public Form1()
{
InitializeComponent();
}
private void Form1(object sender, EventArgs e)
{
sdaHFP = new SqlDataAdapter(QueryDgvHFP, con);
dtHFP = new DataTable();
sdaHFP.Fill(dtHFP);
foreach (DataRow item in dtHFP.Rows)
{
int n = dgvHFP.Rows.Add();
dgvHFP.Rows[n].Cells[0].Value = item["HFP"].ToString();
dgvHFP.Rows[n].Cells[1].Value = item["YearPeriod"].ToString();
if (item["Active"].ToString() == "Y")
{
dgvHFP.Rows[n].Cells[2].Value = true;
}
else
{
dgvHFP.Rows[n].Cells[2].Value = false;
};
dgvHFP.Rows[n].Cells[3].Value = item["ID"].ToString();
}
}这是将数据从Sql查询加载到DataGridView,我在此代码中添加了一个用于执行、更新或插入的按钮:
private void btUpdate_Click(object sender, EventArgs e)
{
try
{
cmbl = new SqlCommandBuilder(sdaHFP);
sdaHFP.Update(dtHFP);
MessageBox.Show("Success", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}当我在DataGridView中更新/插入数据并单击该更新按钮时,将出现一个成功的MessageBox,但数据库中的数据既未更新也未插入
请帮我解决这个问题,为什么更新按钮不能工作?
非常感谢。
发布于 2016-01-27 08:53:13
应该将DataGridView绑定到DataTable,然后在更改单元格值或添加或删除行时,这些更改将应用于DataTable。然后可以使用TableAdapter保存数据表更改。
this.dataGridView1.DataSource = dataTable;注意:用于存储true/false或Yes/No值,最好在server中使用bit数据类型。但在下面的示例中,我假设您需要将值存储为Y/N作为nvarchar(50),然后设置一个DataGridViewCheckBoxColumn以支持编辑字符串列。
示例
假设我们有一个表Table1
Column1: int, primary key
Column2: nvarchar(50), Allows Null, Containing Y or N as vaule我们希望在一个Table1中编辑DataGridView的数据。

下面是可以用来加载、编辑和保存数据的代码:
private DataTable table;
private SqlDataAdapter dataAdapter;
private void sampleForm_Load(object sender, EventArgs e)
{
var command = "SELECT * FROM Table1";
var connection = @"Your connection string";
table = new DataTable();
dataAdapter = new SqlDataAdapter(command, connection);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(table);
//Set false as default value for Column2
table.Columns["Column2"].DefaultValue = false;
var column1 = new DataGridViewTextBoxColumn();
column1.Name = "Column1";
column1.DataPropertyName = "Column1";
var column2 = new DataGridViewCheckBoxColumn();
column2.Name = "Column2";
column2.DataPropertyName = "Column2";
column2.TrueValue = "Y";
column2.FalseValue = "N";
this.dataGridView1.Columns.Add(column1);
this.dataGridView1.Columns.Add(column2);
//Bind grid to table
this.dataGridView1.DataSource = table;
}
private void saveButton_Click(object sender, EventArgs e)
{
//Save data
this.dataGridView1.EndEdit();
dataAdapter.Update(table);
}https://stackoverflow.com/questions/35031201
复制相似问题