我正在尝试创建一个Sharepoint表单,该表单将行添加到Visual C#中的GridView。但是,我只能写第一行-当我单击AddRow时,它只会覆盖我输入的最后一行。我曾尝试使用会话和Page.IsPostBack,但在尝试运行Sharepoint时,它们就会死掉。谢谢!
命名空间VisualWebPartProject3.VisualWebPart1 { 公共局部类VisualWebPart1UserControl:UserControl { 数据表dt;
private void Page_Load(object sender, EventArgs e)
{
// if (!Page.IsPostBack)
//{
dt = new DataTable();
CreateDataTableColumns(dt);
// }
}
private void CreateDataTableColumns(System.Data.DataTable dt)
{
dt.Columns.Add("Title");
dt.Columns.Add("Type");
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void AddRow_Click(object sender, EventArgs e)
{
string title = txtTitle.Text;
string selection = selectionList.Text;
DataRow dr = dt.NewRow();
//addrows
dr["Title"] = title;
dr["Type"] = selection;
dt.Rows.Add(dr);
int count = dt.Rows.Count;
GridView1.DataSource = dt;
GridView1.DataBind();
countTxt.Text = count.ToString();
}
}
}
答案 0 :(得分:1)
您必须跟踪Session或Viewstate中的总行。然后从Viewstate加载项目并添加下一行。 请查看下面的代码段,以便实际操作。
protected void AddRow_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//check if the viewstate exists
if (ViewState["myTable"] != null)
{
//cast the viewstate back to a datatable
dt = ViewState["myTable"] as DataTable;
}
else
{
//add columns to tne new datatable
dt.Columns.Add("Title");
dt.Columns.Add("Type");
//add the table to the viewstate
ViewState["myTable"] = dt;
}
string title = "title " + dt.Rows.Count;
string selection = "selection " + dt.Rows.Count;
DataRow dr = dt.NewRow();
dr["Title"] = title;
dr["Type"] = selection;
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}