Friday, April 8, 2011

How to pass an array to the stored procedure

If you have a situation where you have to pass multiple selected values from the listbox to a stored procedure and these multiple selected values should be used in a filter criteria "IN", you could do it using dynamic sql. Concatenate the list of selected values with comas. If the search criteria are strings, concatenate quotes to the strings and pass this string to the storedprocedure with dynamic sql in it.

string _selList = "";
int[] indSel = DDL.GetSelectedIndices();
foreach (int i in indSel)
{
_selList += "'" + DDLMfgSite.Items[i].Text + "',";
}
if (_selList.LastIndexOf(",") > 0)
_selList = _selList.Substring(0, _selList.LastIndexOf(","));

Populating a Texbox with ListBox multiple selected items using Javascript

function ddlChange() {
var ddl = document.getElementById('<%=DDL.ClientID%>');
var textBox = document.getElementById('<%=txtSelected.ClientID%>');
len = ddl.length;
textBox.value = "";
for (var j = 0; j < len; j++) {
if (ddl.options[j].selected) {
textBox.value += ddl.options[j].text + "\r\n";
}
}
}


<div>Available Items:</div>
<div>
<asp:ListBox ID="DDL" runat="server" SelectionMode="Multiple" onChange="ddlChange()" Height="170px">
</asp:ListBox>
</div>


<div>Selected Items:</div>
<div>
<asp:TextBox ID="txtSelected" runat="server" TextMode="MultiLine"
ReadOnly="true" Height="170px" Width="365px"></asp:TextBox>
</div>

Thursday, April 7, 2011

Setting Textbox to the dropdownlist's selected item using javascript

<script type="text/javascript"/>
function ddlChange() {
var ddl = document.getElementById('<%=DDL.ClientID%>');
var textBox = document.getElementById('<%=txtSelected.ClientID%>');
textBox.value = ddl.options[ddl.selectedIndex].text;
}
</script>

<asp:DropDownList ID="DDL" runat="server" DataTextField="Site" DataValueField="Site" onChange="ddlChange()">
</asp:DropDownList>
<asp:TextBox ID="txtSelected" runat="server" Width="300px"></asp:TextBox>

Setting ListBox scroll position at the Selected Items

If you have a listbox inside your user control and if all of these conditions below apply:
1. Your listbox is inside a user control
2. The user control becomes visible based on other selections on the webform you made.
3. The listbox is bound to the data in the Page_Init and the default SelectedValue is set in the code behind.

In this scenario, when the user control becomes visible, the listbox scroll position is set at the first item in the listbox instead of at the SelectedValue.

If you want the listbox scroll position at the SelectedValue, you have to write javascript.

Write this javascript in your user control:

window.onload = function () {
var ddl = document.getElementById('<%=DDL.ClientID%>');
len = ddl.length;
for (var j = 0; j < len; j++) {
if (ddl.options[j].selected) {
ddl.options[j].selected = false;
ddl.options[j].selected = true;
}
}
}

What you do here is just unselect and reselect the selected items.