1

我想通过 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;

我想将文本框添加到第 4 列,并且我想一一访问。

4

2 回答 2

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();

   }
于 2014-03-19T01:42:49.570 回答
0

没有把握。但希望这段代码对你有所帮助。只需将文本框类型的列添加到您的数据表中。

DataTable table = new DataTable();
DataColumn col = new DataColumn("Name", typeof(TextBoxBase));
table.Columns.Add(col);
于 2013-11-07T13:17:04.257 回答