ASP.NET中动态添加控件,要求每点一次按钮就添加一次控件,最好附源码(原创)

 我来答
wangshuaisupin
2011-05-17 · TA获得超过1884个赞
知道小有建树答主
回答量:805
采纳率:100%
帮助的人:1235万
展开全部
html代码:
<asp:HiddenField ID="hfSelectCount" runat="server" /><asp:HiddenField ID="hfDelIds" runat="server" />
<a href="javascript:addrow();" style="padding:6px; float:right;">添加选项</a>
<table id="tableSelect" border="0" cellpadding="4" cellspacing="1">
<tr><td width="60">序号</td><td>选项内容</td><td width="60">操作</td></tr>
</table>

js代码:
<script type="text/javascript">
var tableSelect = document.getElementById("tableSelect");
var hfSelectCount = document.getElementById("<%=hfSelectCount.ClientID %>");
var hfDelIds = document.getElementById("<%=hfDelIds.ClientID %>");
function addrow()
{
var r = tableSelect.insertRow(tableSelect.rows.length);//插入一行tr
var c = r.insertCell(0);//插入一个单元格td
var rIndex = tableSelect.rows.length - 1;
c.innerHTML = rIndex;
c = r.insertCell(1);
c.innerHTML = "<input type=\"text\" id=\"txtSubject_" + rIndex + "\" name=\"txtSubject_" + rIndex + "\"/>";
c = r.insertCell(2);
c.innerHTML = "<a href='javascript:delrow(" + rIndex + ");'>删除</a>";
hfSelectCount.value = tableSelect.rows.length;
document.getElementById("txtSubject_" + rIndex).focus();
}
function delrow(index)
{
var txtSID = document.getElementById("txtSID_" + index);
if(txtSID)
{
hfDelIds.value += "," + txtSID.value;
}
tableSelect.deleteRow(index);
for(var i = index; i < tableSelect.rows.length;i++)
{
tableSelect.rows[i].cells[0].innerHTML = i;
var txtS = tableSelect.rows[i].cells[1].getElementsByTagName("input");
for(var j = 0; j < txtS.length; j++)
{
if(txtS[j].type == "text")
{
txtS[j].id = "txtSubject_" + i;
txtS[j].name = "txtSubject_" + i;
}
else
{
txtS[j].id = "txtSID_" + i;
txtS[j].name = "txtSID_" + i;
}
}
tableSelect.rows[i].cells[2].innerHTML = "<a href='javascript:delrow("+i+");'>删除</a>";
}
hfSelectCount.value = tableSelect.rows.length;
}
hfSelectCount.value = tableSelect.rows.length;
</script>

后台读取代码:
NameValueCollection nameValue = Request.Form;

//删除选项操作
string[] dels = hfDelIds.Value.Split(',');
foreach (string d in dels)
{
//删除代码
}

//添加修改选项操作
int s_c = Convert.ToInt32(hfSelectCount.Value);
for (int i = 1; i < s_c; i++)
{
string s = nameValue["txtSubject_" + i];
if (!string.IsNullOrEmpty(s))
{
string s_id = nameValue["txtSID_" + i];
m_s.Title = s;
m_s.Contents = s;
//添加代码
}
}

就这么多了,有不懂的地方再问吧
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式