-2

我一直在研究一个问题,我终于弄明白了。我试图在窗体初始化时设置一个控件。我认为控件的值没有被设置是因为控件已经被绘制(如果我错了,请纠正我)。

我的部分表单代码

//in form 1    
....
private void button2_Click(object sender, EventArgs e)
            {
                Form2 form = new Form2();
                form.Owner = this;
                form.Show(this);
            }
....}

    public Form2()
    {
        InitializeComponent();
        setData(); //Sets a datagridview's combobox column and databinds a datatable
        setGrid(); //Sets each row in the datagridview combobox's value to a string 
    }
    private void setData()
    {
        gvTest.AllowUserToAddRows = false;
        string strConn = "server=10.253.3.185;database=petersun-test1;user id=ctore;password=cqi$$;connection timeout=30";
        SqlConnection conn = new SqlConnection(strConn);
        DataTable dit = new DataTable();
        try
        {
            conn.Open();
            string sql = "SELECT LTRIM(RTRIM(COLUMN_NAME)) as ColumnName from INFORMATION_SCHEMA.COLUMNS where Table_Name='coproc' order by ORDINAL_POSITION";
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dit);

            DataGridViewComboBoxColumn dcDatabasefields = new DataGridViewComboBoxColumn();
            dcDatabasefields.DataPropertyName = "ColumnName";
            dcDatabasefields.HeaderText = "Database Field Name";
            dcDatabasefields.Name = "dbFields";
            dcDatabasefields.DisplayMember = "ColumnName";
            dcDatabasefields.ValueMember = "ColumnName";
            dcDatabasefields.Width = 200;
            BindingSource bsourceFields = new BindingSource();
            bsourceFields.DataSource = dit;
            dcDatabasefields.DataSource = bsourceFields;

            dcDatabasefields.DataSource = dit; // bsourceFields;
            gvTest.Columns.Add(dcDatabasefields);
        }
        finally
        {
            conn.Close();
        }

        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("options");
        dt.Columns.Add(dc);
        DataRow dr = dt.NewRow();
        dr["options"] = "A";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["options"] = "C";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["options"] = "D";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["options"] = "E";
        dt.Rows.Add(dr);
        gvTest.DataSource = dt;
    }
private void setGrid()
{
 foreach(DataGridView Row in gvGrid.Rows)
 {
   Row.Cells[0].Value = "string";
  }
}

所以我认为正在发生的是: 1. 组件正在初始化 2. 使用列创建 datagridview 3. 设置列值 4. 绘制表单

我的想法正确吗?我的问题是我应该设置控件的值是什么表单事件?我做了一些研究,我正在考虑 PAINT 事件,但我也不确定。有人可以详细解释表格的生命周期或指出我的某个地方。谢谢

4

1 回答 1

0

我刚刚将编码添加到 Form_load 中,并将值添加到网格中

于 2013-08-18T20:49:04.800 回答