DataGridView CheckBox列 - 显示CheckBox但存储字符串

时间:2016-01-27 07:29:55

标签: c# .net winforms checkbox datagridview

这是我的代码:

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 Query加载数据到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中更新/插入数据并单击该更新按钮时,会出现成功消息框,但数据库中的数据未更新也未插入

请帮我解决这个问题,为什么更新按钮不起作用?

非常感谢。

1 个答案:

答案 0 :(得分:0)

您应该将private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { Item removed = e.RemovedItems.FirstOrDefault() as Item; if (removed != null) { removed.IsReadOnly = true; } Item added = e.AddedItems.FirstOrDefault() as Item; if (added != null) { added.IsReadOnly = false; } } 绑定到DataGridView,然后在更改单元格值或添加或删除行时,更改将应用​​于DataTable。然后,您可以使用DataTable

保存数据表更改
TableAdapter

注意:要存储this.dataGridView1.DataSource = dataTable; true/false值,最好在sql server中使用Yes/No数据类型。但在下面的示例中,我认为您需要将值bit存储为Y/N,并设置nvarchar(50)以支持编辑字符串列。

示例

假设我们有一个表DataGridViewCheckBoxColumn

Table1

我们想要编辑Column1: int, primary key Column2: nvarchar(50), Allows Null, Containing Y or N as vaule 中的Table1数据:

enter image description here

以下是可用于加载,编辑和保存数据的代码:

DataGridView