我在数据gridview中动态添加了该列,并希望为其分配一些值。我正在使用以下代码...
String qr = "SELECT Id, CONVERT(varchar, OrderItemId) AS Product, Quantity,CONVERT(varchar,CustomerId) AS Customer, ReturnRequestStatusId as'Return Request Status', CreatedOnUtc as Date FROM ReturnRequest";
DataTable dtr = new DataTable();
tp.populatedt(qr, dtr);
dgvReturnRequests.DataSource = dtr;
DataGridViewTextBoxColumn ord = new DataGridViewTextBoxColumn();
ord.HeaderText = "Order #";
ord.Name = "OrderCol";
dgvReturnRequests.Columns.Insert(4, ord); // Here I added a new column
foreach (DataGridViewRow dr in dgvReturnRequests.Rows)
{
string s = dr.Cells[1].Value.ToString();
DataTable pn = new DataTable();
tp.populatedt("Select p.pname,o.OrderId from Product p JOIN OrderItem o on p.Id=o.ProductId where o.Id='" + Convert.ToInt32(s) + "'", pn);
foreach (DataRow dr1 in pn.Rows)
{
dr.Cells[1].Value = dr1["pname"].ToString();
dr.Cells[4].Value = dr1["OrderId"].ToString(); // Here I am adding the value in a newly added column
}
}
显示了产品名称(pname),但是dr1 [“ OrderId”]。ToString()的值未显示在该单元格中...检查下图中的输出。
我该如何解决?
答案 0 :(得分:1)
您应确保dgvReturnRequests.Rows和pn.Rows不为空。否则,将无法达到循环且不会更新任何内容。
在方法的最后,您应该调用 dgvReturnRequests.Update() ;;更新数据网格视图。
答案 1 :(得分:0)
也许是因为您没有重新绑定gridview控件:
String qr = "SELECT Id, CONVERT(varchar, OrderItemId) AS Product, Quantity,CONVERT(varchar,CustomerId) AS Customer, ReturnRequestStatusId as'Return Request Status', CreatedOnUtc as Date FROM ReturnRequest";
DataTable dtr = new DataTable();
tp.populatedt(qr, dtr);
dgvReturnRequests.DataSource = dtr;
DataGridViewTextBoxColumn ord = new DataGridViewTextBoxColumn();
ord.HeaderText = "Order #";
ord.Name = "OrderCol";
dgvReturnRequests.Columns.Insert(4, ord);
foreach (DataGridViewRow dr in dgvReturnRequests.Rows)
{
string s = dr.Cells[1].Value.ToString();
DataTable pn = new DataTable();
tp.populatedt("Select p.pname,o.OrderId from Product p JOIN OrderItem o on p.Id=o.ProductId where o.Id='" + Convert.ToInt32(s) + "'", pn);
foreach (DataRow dr1 in pn.Rows)
{
dr.Cells[1].Value = dr1["pname"].ToString();
dr.Cells[4].Value = dr1["OrderId"].ToString(); // Here I am adding the value in a newly added column
}
dtr.add(dr); // Function may differ in name. Maybe add a row.
}
dgvReturnRequests.DataSource=dtr;
dgvReturnRequests.DataBind();