最初我的gridview与一个数据绑定,当用户单击添加更多按钮时,我一次通过jquery将一行添加到gridview。我的代码工作正常,但问题是当我通过 jquery 从客户端向 gridview 添加 5 行时,当我尝试从服务器端迭代这些行时,GridView1.Rows.Count
总是返回一行。所以我的问题是,当 jquery 从客户端添加行时,我无法从服务器端迭代行集合。所以在这里我给出我的整个代码,只是告诉我我能做什么,结果我将能够在通过 jquery 添加这些行后从服务器端读取所有行。
ASPX
<script>
$(document).ready(function () {
$("#datepicker").datepicker({
dateFormat: 'dd/mm/yy',
showOn: "both",
buttonImageOnly: true,
buttonImage: "images/date_picker.gif",
buttonText: "Calendar"
});
$('#<%=btnAdd.ClientID %>').bind('click', function (event) {
var $grid = $('#<%=GridView1.ClientID %>');
var $row = $grid.find('tr:last').clone().appendTo($grid);
$row.find('select')[0].selectedIndex = 0;
return false;
});
});
</script>
<asp:Button ID="btnAdd" Text="Add More" runat="server" /><br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowHeader="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>India</asp:ListItem>
<asp:ListItem>UK</asp:ListItem>
<asp:ListItem>USA</asp:ListItem>
<asp:ListItem>Germany</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlCity" runat="server">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>Kolkata</asp:ListItem>
<asp:ListItem>Mumbai</asp:ListItem>
<asp:ListItem>Delhi</asp:ListItem>
<asp:ListItem>Madras</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br /><br />
<asp:Button ID="Button1" Text="Read gridview Value" runat="server"
onclick="Button1_Click" /><br />
服务器端代码
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
DataRow dr = dt.NewRow();
dr["ID"] = "";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb=new StringBuilder();
//HtmlTable table = (HtmlTable)rpt.Items[0].FindControl("tblSample");
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
string country = ((DropDownList)GridView1.Rows[i].FindControl("ddlCountry")).SelectedItem.Text;
string city = ((DropDownList)GridView1.Rows[i].FindControl("ddlCity")).SelectedItem.Text;
sb.Append("Country :- " + country + " City :- " + city);
}
txtData.Text = sb.ToString();
}