Reputation: 248
i am trying to save selected item on listbox in a single column in database as comma separated.
<td>
<%--<asp:DropDownList ID="ddlCertific" runat="server" class='form-control'></asp:DropDownList>--%>
<asp:ListBox ID="ddlCertific" runat="server" SelectionMode="Multiple">
</asp:ListBox>
</td>
binding data on page load
void BindDropdown()
{
dt = conn.GetData("SELECT CODE_DESC as datac from code ");
ddlCertific.DataSource = dt;
ddlCertific.DataTextField = "datac";
ddlCertific.DataValueField = "datac";
ddlCertific.DataBind();
}
Datasaving in database
protected void submit(object sender, EventArgs e)
{
string CERTIFIC;
CERTIFIC = ddlCertific.Text;
conn.IUD("INSERT INTO BAM(CERTIFIC) values ('"+ CERTIFIC +"')");
}
Any idea would be appreciated.
Upvotes: 0
Views: 356
Reputation: 2133
Here are the steps after some research and it is working for me
Added listbox as per question
<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>
Added a hidden field - Tricky part
<asp:HiddenField runat="server" ID="HiddenField1" ClientIDMode="Static" OnValueChanged="Date_ValueChanged" />
Javascript - This will add the selected items in the listbox using a ',' and do a post back since we need value at server
<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>
Add client postback reference on server side and hiddenfield change event.
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
}
Upvotes: 1