views:

43

answers:

1

I am new at this. I am trying to populate a datagrid from a table source. My code is attempting to do two things. First it populates a dataGrid with columns from a table. Then it adds a column called "SELECT" at the end of the grid. This select is CheckBox. However, when I execute this code, it adds the "SELECT" column twice. I want to see it once. What am I doing wrong?

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);
}
+4  A: 

Your problem is that the databindingcomplete event happens more then you think. In fact anytime some data changes it will fire.

You need to add the column outside of the databindingcomplete event.

EDIT

Actually since you are databinding, you may want to consider adding the column to your datatable. You would do this before the binding the datatable to the grid. Essentially, just create a datacolumn named select, that has the type of boolean and then add the datacolumn to the datatable.

Tony Abrams
Thanks Tony! Which event do you recommend?
abhi
Actually, I added an edit. You really should just think about adding a column to the datatable right before you bind it to the grid.
Tony Abrams