我有一个表单,它接受3个值Name,Weight,Breed和2个值是动态生成的,1是datatime,另一个是使用weight计算的Size。单击“添加”按钮后,数据应添加到DataTable并显示在GridView中。
对于第一个输入时间它的工作正常...但是如果我再次填充表格,那么GridView将丢失第一行数据并且仅显示最新数据。我试图通过(!isPostback)纠正它,但现在它显示错误"输入数组比这个表中的列数长。"
以下是代码
public partial class Datatables : System.Web.UI.Page
{
DataTable dtable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblSatus.Text = string.Empty;
prepare();
}
lblSatus.Text += "Outside postback pageload"+dtable.Columns.Count.ToString()+"<br>";
}
private void prepare()
{
if (dtable.Columns.Count == 0)
{
dtable.Columns.Add("Weight", typeof(int));
dtable.Columns.Add("Name", typeof(string));
dtable.Columns.Add("Breed", typeof(string));
dtable.Columns.Add("size", typeof(char));
dtable.Columns.Add("Date", typeof(DateTime));
lblSatus.Text += "DataTable Created with " + dtable.Columns.Count.ToString() + " Columns <br>";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
AddDogData(txtName.Text,Convert.ToInt32(txtWeight.Text), txtBreed.Text);
GridView1.DataSource = dtable;
GridView1.DataBind();
lblSatus.Text += "Added data to Datatable<br>";
}
static DataRow AddDogData(string name,int weight,string breed)
{
return dtable.Rows.Add(weight, name, breed, GetSizeChar(weight), DateTime.Now);
}
static char GetSizeChar(int weight)
{
if (weight >= 100)
return 'B';
else if (weight > 50 && weight < 100)
return 'M';
else
return 'S';
}
}
}