我已经在这个主题上执行了大量的Google搜索,但是无法真正找到这个问题的正确答案。解决方案可能很简单,但我是C#ASP.NET的初学者。我们如何将单个列表分配为gridview列?
我有一些代码将下拉列表和文本框中的用户输入存储并存储到其单独的列表中。我试图在单个gridview中将这两个列表显示为单个列。例如,当用户选择一个产品并输入数量并点击添加按钮时,它应该在gridview的单行中显示详细信息。现在我已经实现将数据保存到列表中,但无法将其显示在单行中。
这里是我的代码:
List<string> productIdList = new List<string>();
List<string> productTemp = new List<string>();
List<string> quantityList = new List<string>();
List<string> quantityTemp = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
productTemp = (List<string>)ViewState["productId"];
quantityTemp = (List<string>)ViewState["quantity"];
string str1 = Convert.ToString(productTemp);
string str2 = Convert.ToString(quantityTemp);
if (str1 != "")
{
if (productTemp.Count != 0)
{
foreach (string ids in productTemp)
{
productIdList.Add(ids);
}
}
}
if (str2 != "")
{
if (quantityTemp.Count != 0)
{
foreach (string qtys in quantityTemp)
{
quantityList.Add(qtys);
}
}
}
}
}
protected void btnContinue_Click(object sender, EventArgs e)
{
productIdList.Add(ddlProduct.SelectedValue.ToString());
quantityList.Add(txtQuantity.Text);
ViewState["productId"] = productIdList;
ViewState["quantity"] = quantityList;
txtQuantity.Text = "";
ArrayList testList = new ArrayList();
testList.AddRange(productIdList);
testList.AddRange(quantityList);
grdTest.DataSource = testList;
grdTest.DataBind();
grdProduct.DataSource = productIdList;
grdProduct.DataBind();
grdQuantity.DataSource = quantityList;
grdQuantity.DataBind();
}
}
在GridView当前存在的测试目的是检查是否按钮的每次点击后的数据仍然存在。 grdTest是我用来试图将列表显示为列的内容。
最后会是这样的:
名称 数量
----- -----
名1(列表1) 5(列表2)
谢谢!
太棒了!这实际上是我想要的方式。我有问题,你能解释一下它究竟做什么吗?我以前从未使用过linq。再次感谢! :) – Zain1291