cs code
protected void DeleteNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["dtCurrentTable"] != null)
{
DataTable DeldtCurrentTable = (DataTable)ViewState["dtCurrentTable"];
DataRow drCurrentRow = null;
if (DeldtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i > DeldtCurrentTable.Rows.Count; i--)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
//TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
DropDownList box2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("ddldatatype");
drCurrentRow = DeldtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i - 1;
drCurrentRow["Column1"] = box1.Text;
drCurrentRow["Column2"] = box2.Text;
//drCurrentRow["Column3"] = box3.Text;
rowIndex--;
}
//add new row to DataTable
DeldtCurrentTable.Rows.Remove(drCurrentRow);
//Store the current data to ViewState
ViewState["dtCurrentTable"] = DeldtCurrentTable;
//Rebind the Grid with the current data
Gridview1.DataSource = DeldtCurrentTable;
Gridview1.DataBind();
}
}
}
protected void ButtonDel_Click(object sender, EventArgs e)
{
DeleteNewRowToGrid();
}
aspx code
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Column Name">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%-- <asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Data Type">
<ItemTemplate>
<asp:DropDownList ID="ddldatatype" runat="server">
<asp:ListItem>varchar</asp:ListItem>
<asp:ListItem>int</asp:ListItem>
<asp:ListItem>numeric</asp:ListItem>
<asp:ListItem>uniqueidentifier</asp:ListItem>
<asp:ListItem>char</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/>
<asp:Button ID="ButtonDel" runat="server" Text="Delete Row" OnClick="ButtonDel_Click"/>
<input type="hidden" runat="server" value="0" id="hiddencount" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
I have done with add rwo, now I want to delete
答案 0 :(得分:0)
你试图删除一条甚至不在你的DataTable中的“drCurrentRow”行,因为你自己创建了这个drCurrentRow = DeldtCurrentTable.NewRow();
,甚至没有插入它(反正没用)。
您必须搜索要从源中删除的行,如下所示:
var toDel = DeldtCurrentTable.Where(row => /* true if found */).ToArray();
foreach(var t in toDel) DeldtCurrentTable.Rows.Remove(t);
然后你可以重复并重新设置你的rownumbers。
最终设置ViewState和DataSource + DataBind
顺便说一下:你的命名真令人沮丧 - “DeleteNewRowToGrid”的意思是什么?你想删除一些新行吗? 在这种情况下,是一个新行? 那么:这里应该删除哪一行?