如何将textBox添加到Winform dataGridView单元格

时间:2013-11-07 12:46:14

标签: c#

我想通过for循环将textBox添加到我的列单元格中......

我的代码:

DataTable dt = new DataTable();

DataColumn dc;
dc = new DataColumn("No");
dt.Columns.Add(dc);
dc = new DataColumn("Item");
dt.Columns.Add(dc);
dc = new DataColumn("Available Stock");
dt.Columns.Add(dc);
dc = new DataColumn("Quantity");
dt.Columns.Add(dc);
dc = new DataColumn("Price");
dt.Columns.Add(dc);

// Define  rows
for (int i = 0; i < count; i++)
{
    string no = dtr.Rows[i][0].ToString();
    string item = dtr.Rows[i][2].ToString() + " " + dtr.Rows[i][1].ToString();
    string A_qty = dtr.Rows[i][3].ToString();
    string price = dtr.Rows[i][4].ToString();

    dt.Rows.Add(no, item, A_qty,"[i want to add text box here] " ,price);        
}

dataGridView1.DataSource = dt;

我想将textBoxes添加到第4列,我希望逐个访问。

2 个答案:

答案 0 :(得分:2)

您可以将textBox列添加到DataGridView,然后循环遍历DataGridView,如

DataTable dt=new DataTable();

dt.Columns.Add("No",typeof(int));

dt.Columns.Add("Item",typeof(string));

dt.Columns.Add("quantity",typeof(int));

dt.Columns.Add("Price",typeof(decimal));

//Add row to the datatable

for (int i = 0; i < count; i++)
{

//Not Sure what dtr is you looping through

    string no = dtr.Rows[i][0].ToString();
    string item = dtr.Rows[i][1].ToString() + " " + dtr.Rows[i][1].ToString();
    string A_qty = dtr.Rows[i][2].ToString();
    string price = dtr.Rows[i][3].ToString();

    dt.Rows.Add(no, item, A_qty, price);        
}


//Create New DataGridViewTextBoxColumn
DataGridViewTextBoxColumn textboxColumn=new DataGridViewTextBoxColumn();

//Bind DataGridView to Datasource
dataGridView1.datasource=dt;

//Add TextBoxColumn dynamically to DataGridView
 dataGridView1.Columns.Add(textboxColumn);

//Loop through DataGridView
 foreach (DataGridViewRow row in dataGridView1.Rows)

{

     //Do your task here
      string fourthColumn = row.Cells[4].Value.toString();

   }

答案 1 :(得分:0)

不确定。但希望这段代码可以帮到你。只需将textbox类型的列添加到数据表中即可。

DataTable table = new DataTable();
DataColumn col = new DataColumn("Name", typeof(TextBoxBase));
table.Columns.Add(col);