在动态创建表单时将值置于控件中

时间:2013-08-15 21:35:45

标签: c# winforms

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

我的部分表单代码

//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事件,但我也不确定。有人可以详细解释表格的生命周期或指向某个地方。 感谢

1 个答案:

答案 0 :(得分:0)

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