问题
I have asp:DropDownList wich is populated from SQLdatasource and I need to set selected items on select list (asp:DropDownList or asp:DropDownList).
Here is my code:
<asp:SqlDataSource runat="server" ID="sqlAihealueet"
ConnectionString="Server=SQL2008;Database=Data;UID=123;PWD=123"
SelectCommand="SELECT TOP (100) PERCENT valikkoaktiivinen, alue, id, otsikko, osa1b, osa2b, osa3b, osa4b FROM dbo.FiValikko"></asp:SqlDataSource>
<asp:DropDownList name="aihevalinta" id="aihevalinta" multiple="true" DataSourceid="sqlAihealueet" DataValueField="id" DataTextField="otsikko" class="populate placeholder" style="width:450px; font-size:11px" runat="server">
</asp:DropDownList>
On this page I have all other fields set up on codebehind like this:
vapaaselite.text = drRow.Item("vapaaselitetxt").ToString
How should I make that multiple selected ones to that select list on?
I have tryed this (aihealueet data = "9682,9683"):
aihevalinta.SelectedValues = drRow.Item("aihealueet")
not working, gives me error: SelectedValues' is not a member of 'System.Web.UI.WebControls.DropDownList
Is there way I could make selecteced items straight from sql datasource, from SQLquery? I could mark them easily on SQLquery.
...or how Do I do this with asp:Listbox? I tryed same kind of aproach. I only can get one item as selected. If I try to make other one selected too the first selected ones select state disappears.
aihevalinta.SelectedValue = "9565"
aihevalinta.SelectedValue = "9566"
The best solution for me would be to mark selected one straigt from SQldatasource (same where the list comes form). data would be like this:
回答1:
If I understand correctly you would like to fill your DropDownList with multiple values, something like this:
It is possible, I do it in this way:
Markup:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
</asp:DropDownList>
Code behind:
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "select * from Pagamenti ORDER BY [Data] DESC";
com = new SqlCommand(str, con);
sqlda = new SqlDataAdapter(com);
ds = new DataSet();
sqlda.Fill(ds, "Pagamenti");
string spacer = " --|-- ";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DropDownList1.Items.Add(string.Format("{0:Id ####}", ds.Tables[0].Rows[i]["Id"]) +
spacer + Convert.ToDateTime(ds.Tables[0].Rows[i]["Data"]).ToString("dd/MM/yyyy") +
spacer + string.Format("{0:R #.###,##}", (ds.Tables[0].Rows[i]["Somma"])));
}
con.Close();
}
Let us know if this is what you where looking for.
回答2:
I had to make work around to my problem. I'am sure there have to some better way to do this.
My work around were done using some jquery script and non visible asp.net textbox field (valinnatlista).
<script>
var data= $("#valinnatlista").val() ;
var dataarray=data.split(",");
$("#aihevalinta").val(dataarray);
$("#aihevalinta").multiselect("refresh");
</script>
来源:https://stackoverflow.com/questions/25745204/aspdropdownlist-selectedvalues-in-multiple-selection-list