我正尝试将所选项目在列表框中的数据库中以逗号分隔保存在单列中。
<td>
<%--<asp:DropDownList ID="ddlCertific" runat="server" class='form-control'></asp:DropDownList>--%>
<asp:ListBox ID="ddlCertific" runat="server" SelectionMode="Multiple">
</asp:ListBox>
</td>
在页面加载时绑定数据
void BindDropdown()
{
dt = conn.GetData("SELECT CODE_DESC as datac from code ");
ddlCertific.DataSource = dt;
ddlCertific.DataTextField = "datac";
ddlCertific.DataValueField = "datac";
ddlCertific.DataBind();
}
数据库中的数据保存
protected void submit(object sender, EventArgs e)
{
string CERTIFIC;
CERTIFIC = ddlCertific.Text;
conn.IUD("INSERT INTO BAM(CERTIFIC) values ('"+ CERTIFIC +"')");
}
任何想法都会受到赞赏。
答案 0 :(得分:1)
这是经过一些研究的步骤,它对我有用
根据问题添加了列表框
<asp:ListBox ID="ddlCertific" runat="server" SelectionMode="Multiple" Width="229px">
<asp:ListItem Value="test1">test1</asp:ListItem>
<asp:ListItem Value="test2">test2</asp:ListItem>
<asp:ListItem Value="test3">test3</asp:ListItem>
<asp:ListItem Value="test4">test4</asp:ListItem>
</asp:ListBox>
添加了隐藏字段-棘手的部分
<asp:HiddenField runat="server" ID="HiddenField1" ClientIDMode="Static" OnValueChanged="Date_ValueChanged" />
Javascript-这将使用','将选择的项目添加到列表框中,并进行回发,因为我们需要服务器上的价值
<script type="text/javascript">
function getSelectedOptions(sel) {
var opts = [], opt;
var a = [];
// loop through options in select list
for (var i=0, len=sel.options.length; i<len; i++) {
opt = sel.options[i];
// check if selected
if ( opt.selected ) {
// add to array of option elements to return from this function
opts.push(opt);
a.push(opt.value + ', ');
}
}
document.getElementById('HiddenField1').value = a.toString();
// return array containing references to selected option elements
return opts;
}
document.getElementById('ddlCertific').onchange = function (e)
{
getSelectedOptions(this);
abc();
//__doPostBack
};
function abc() {
document.getElementById('HiddenField1').value;
__doPostBack('HiddenField1');
}
</script>
在服务器端和hiddenfield更改事件中添加客户端回发引用。
protected void Page_Load(object sender, EventArgs e)
{
string val = ClientScript.GetPostBackEventReference(this,"");
}
protected void Date_ValueChanged(object sender, EventArgs e)
{
string value = HiddenField1.Value;
//do your db stuffs
}