更新2: 基本上,你需要使用意見去管理一切。下面我已經提到過,用簡單的話來說,你可以添加,編輯,刪除ViewState中的記錄並將它們綁定到gridview。
protected void Page_Load(object sender, EventArgs e)
{
try
{
//Adding data to datatable
DataRow t = tablaPed.NewRow();
//adding data to row
t["SrNo"] = "1";
t["EmailId"] = "[email protected]";
t["Password"] = "Password";
//adding row to table
tablaPed.Rows.Add(t);
//saving databale into viewstate
ViewState["UserDetail"] = t;
//bind Gridview
GridView1.DataSource = t;
GridView1.DataBind();
}
}
下方的funtion調用添加按鈕被點擊時:
private void AddNewRecordRowToGrid()
{
// check view state is not null
if (ViewState["UserDetail"] != null)
{
//get datatable from view state
DataTable dtCurrentTable = (DataTable)ViewState["UserDetail"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
//this will add previously added entries
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//add each row into data table
drCurrentRow = dtCurrentTable.NewRow();
//you can add data from textbox or other user control
drCurrentRow["SrNo"] = "2";
drCurrentRow["EmailId"] = "[email protected]";
drCurrentRow["Password"] = "Password";
}
//Remove initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
//add created Rows into dataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Save Data table into view state after creating each row
ViewState["UserDetail"] = dtCurrentTable;
//Bind Gridview with latest Row
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
}
protected void btAgregaT_Click(object sender, EventArgs e)
{
AddNewRecordRowToGrid();
}
我希望它可以幫助你理解:)
考慮tablaPed爲全球數據表對象。下面 實例是加入行到表的標準方式:
//creating the table if you already have it then no need to add it.
DataTable dt = new DataTable();
//Defining the table structure. If you already have defined DataTable you dont need to define it either.
dt.Columns.Add("SrNo");
dt.Columns.Add("EmailId");
dt.Columns.Add("Password");
//Creating a object of DataRow using object of desired table (Basically cloning a row)
DataRow drNew = dt.NewRow();
//Adding data to each row
drNew["SrNo"] = "1";
drNew["EmailId"] = "[email protected]";
drNew["Password"] = "Password";
//adding this newly added row our table
dt.Rows.Add(drNew);
你的情況:
protected void btAgregaT_Click(object sender, EventArgs e)
{
//cloning the table row
DataRow t = tablaPed.NewRow();
//adding data to row
t["SrNo"] = "1";
t["EmailId"] = "[email protected]";
t["Password"] = "Password";
//adding row to table
tablaPed.Rows.Add(t);
}
是什麼tablaPed'的'類型是'DataTable' –
'tablaPed.Rows.Add(DDLArticulos.SelectedItem.ToString(),TBCantidad.Text);' – Damith