我创建了两个TextBox,用于在Visual Studio 2010上使用C#在基于Web的ASP.NET应用程序中输入员工的FirstName和LastName。有一个Button。当我单击它时,我在TextBox中输入的值应该显示在Gridview中,而这些值不会存储在数据库中。我已经使用ArrayList实现了它,如下所示。但现在我想使用通用列表(Typed List)来实现它。我怎样才能做到这一点?您能提供一个示例代码来执行上述功能吗?
我如何调整下面给出的代码,使用通用列表(类型列表)实现功能?
**
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
ArrayList arr;
if (Session["array"] == null)
{
arr = new ArrayList();
}
else
{
arr = (ArrayList)Session["array"];
}
arr.Add(txtName.Text + "," + txtCity.Text); //store textbox values in the array list
Session["array"] = arr;
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("City");
for (int i = 0; i < arr.Count; i++)
{
string[] arrVal;
arrVal = arr[i].ToString().Split(',');
dt.Rows.Add(arrVal[0], arrVal[1]);
}
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
**
答案 0 :(得分:1)
您可以使用List<string>
代替ArrayList
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
List<string> list;
if (Session["list"] == null)
{
list = new List<string>();
}
else
{
list = (List<string>)Session["list"];
}
list.Add(txtName.Text + "," + txtCity.Text); //store textbox values in the array list
Session["list"] = list;
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("City");
for (int i = 0; i < list.Count; i++)
{
string[] arrVal;
arrVal = list[i].ToString().Split(',');
dt.Rows.Add(arrVal[0], arrVal[1]);
}
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
更好的方法可能是:
如果您将类定义为:
class Employee
{
public string FirstName { get; set; }
public string City { get; set; }
}
然后:
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
List<Employee> list;
if (Session["list"] == null)
{
list = new List<Employee>();
}
else
{
list = (List<Employee>)Session["list"];
}
list.Add(new Employee() { FirstName = txtName.Text, City = txtCity.Text }); //store textbox values in the array list
Session["list"] = list;
gvDisplay.DataSource = list; //directly bind the list to the grid
gvDisplay.DataBind();
}