Skip to main content
 首页 » 编程设计

c#之Datagrid绑定(bind)问题

2024年02月24日26虾米姐

我是新手。我正在尝试从表源填充数据网格。我的代码试图做两件事。 首先,它使用表中的列填充数据网格。然后它在网格的末尾添加一个名为“SELECT”的列。这个选择是CheckBox。但是,当我执行此代码时,它会两次添加“SELECT”列。 我想看一次。 我做错了什么?

private void BankFlow_Load(object sender, EventArgs e) 
{ 
    initMethod(); 
    dataTable = getBankFlowData(globalConnection); 
    dataGridView1.DataSource = dataTable; 
} 
 
private static DataTable getBankFlowData(OracleConnection oc) 
{ 
    DataTable dt = new System.Data.DataTable(); 
    try 
    { 
 
        OracleCommand od = oc.CreateCommand(); 
        od.CommandText = "SELECT * FROM BANK_FLOW_SOURCE"; 
        od.CommandType = System.Data.CommandType.Text; 
        OracleDataAdapter adapter = new OracleDataAdapter(od); 
        adapter.Fill(dt); 
 
    } 
    catch (Exception) 
    {  
 
    } 
    return dt; 
} 
 
private static void initMethod() 
{ 
    targetSystem = ConfigurationManager.ConnectionStrings["prototype"].ConnectionString.ToString(); 
    Console.WriteLine("Target : {0}", targetSystem); 
    sourceSystem = ConfigurationManager.ConnectionStrings["qlprod8"].ConnectionString.ToString(); 
    Console.WriteLine("Source : {0}", sourceSystem); 
 
    globalConnection.ConnectionString = sourceSystem; 
    globalConnection.Open(); 
} 
 
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
{ 
    DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn(); 
    col.HeaderText = "SELECT"; 
    col.ReadOnly = false; 
    col.DefaultCellStyle.BackColor = Color.Beige; 
    dataGridView1.Columns.Add(col); 
} 

请您参考如下方法:

您的问题是 databindingcomplete 事件发生的次数比您想象的要多。事实上,只要有一些数据发生变化,它就会触发。

您需要在数据绑定(bind)完成事件之外添加该列。

编辑

实际上,由于您正在进行数据绑定(bind),因此您可能需要考虑将列添加到您的数据表中。您将在将数据表绑定(bind)到网格之前执行此操作。本质上,只需创建一个名为 select 的数据列,它具有 bool 类型,然后将数据列添加到数据表中。