我最终迭代了网格并在每次迭代中创建了文本框和标签。
void Generate_TextBoxes()
{
// top of textboxes
int current_top=150;
int current_left = 1000;
// index used to match between each textbox and the properate column in grid
int my_index = -1;
// iterate the grid and create textbox for each column
foreach (DataGridViewColumn col in dataGridView_add_customer.Columns)
{
my_index++;
// generate textboxes only for visible columns
if (col.Visible == true)
{
// increase the top each time for space between textboxes
current_top += 40;
// create a second column of textboxes (not all of them in 1 long column)
if (my_index == 6) { current_top = 190; current_left = 450; }
TextBox t = new TextBox();
t.Top = current_top;
t.Left = current_left;
t.Width = 170;
t.TextChanged +=new EventHandler(t_TextChanged);
// give an 'id' for each textbox with the corresponding index of the grid
t.Name = my_index.ToString();
Label l = new Label();
l.Text = col.HeaderCell.Value.ToString();
l.Top = current_top;
l.Left = current_left + 190;
this.Controls.Add(l);
this.Controls.Add(t);
}
以及将文本框绑定到网格的函数:
void t_TextChanged(object sender, EventArgs e)
{
// create a reference in order to be able to access grid properties such as rows..
TextBox tt = (TextBox)sender;
// access the correct cell in the grid using the Name property you gave to the textbox (it was name=current_index..)
dataGridView_add_customer.Rows[0].Cells[int.Parse(tt.Name)].Value = tt.Text;
}