Populate a dropdownlist with objectdatasource - c#

I'm trying to populate a dropdownlist with an objectdatasource programatically. It's a user control, so in my ascx I have this:
<asp:ObjectDataSource ID="odsFicheros" runat="server"
OldValuesParameterFormatString="original_{0}"
onselecting="odsFicheros_Selecting" SelectMethod="ejecutaconsultaFicheros" TypeName="DatosGW.ControlBuscador">
</asp:ObjectDataSource>
<asp:DropDownList ID="cmbFicheros" runat="server" CssClass="form-control"
DataTextField="fichero" DataValueField="fichero" DataSourceID="odsFicheros"
ondatabound="cmbFicheros_DataBound" AutoPostBack="True"
onselectedindexchanged="cmbFicheros_SelectedIndexChanged">
</asp:DropDownList>
On the code behind I do this:
protected void Page_Load(object sender, EventArgs e)
{
odsFicheros.TypeName = "DatosGW.ControlBuscador";
odsFicheros.SelectMethod = "ejecutaconsultaFicheros";
Parameter consultas = new Parameter(consulta, TypeCode.String);
odsFicheros.SelectParameters.Add(consultas);
odsFicheros.DataBind();
cmbFicheros.DataSource = odsFicheros;
this.ejecutarConsulta();
}
And finally on my ControlBuscador class I have the method which returns a datatable, but it doesn't work, why?. If you need more details, please let me know it.

In Visual Studio, I did this with the wizard on the Selectin property:
e.InputParameters["consulta"] = hfConsulta.Value;
I created a HiddenField with the parameter I want, so now it's working

Related

Code Behind can't find a nested SQL connection in a List View

I have one ListView nested in another one as follows:
<asp:ListView ID="ListView1" runat="server" DataSourceID="editorMenuLinks" OnDataBound="ListView1_DataBound">
<ItemTemplate>
<asp:ListView ID="ListView2" runat="server" DataSourceID="test2" DataKeyNames="ID_connection" InsertItemPosition="LastItem">
</asp:ListView>
<asp:SqlDataSource runat="server" ID="test2">
</asp:SqlDataSource>
</ItemTemplate>
Code Behind
protected void ListView1_DataBound(object sender, EventArgs e)
{
test2.SelectParameters["-------"].DefaultValue = HttpContext.Current.User.Identity.GetUserId();
}
Unfortunately the SqlDataSource test2 can't be found in code behind. I get an error that the connection (test2) doesn't exist in the current context. Any tip?
Thanks
You can find controls inside the listview by doing
Listview1.FindControl("Name of Control")
Assign this to an instance of a sqlDataSource for example.
Dim Test2 as SqlDataSource = Listview1.FindControl("Test2")

ASP.NET Get value from DropDownList in EditItemTemplate in codebehind

I have a GridView that I have placed in DropDownList's in 2 columns.
<asp:TemplateField HeaderText="Upgrade" SortExpression="Upgrade">
<ItemTemplate>
<asp:Label ID="LabelUpgrade" runat="server" Text='<%# Eval("Upgrade") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlUpgrade" runat="server" Width="100px">
<asp:ListItem Value="1">--Select--</asp:ListItem>
<asp:ListItem Value="2">1</asp:ListItem>
<asp:ListItem Value="3">2</asp:ListItem>
<asp:ListItem Value="4">3</asp:ListItem>
<asp:ListItem Value="5">4</asp:ListItem>
<asp:ListItem Value="6">5</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
how do I grab the item from ddlUpgrade in the codebehind?
OnUpdating Event - I don't have a way to pull the row to get the value from the drop down but I add my sql parameters here.
protected void IAP_Updating(object sender, SqlDataSourceCommandEventArgs e){}
RowUpdating Event - I can get the row here but I can't add the value to the sql parameters because e.command isn't valid here
protected void gvClients_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow _row = gvClients.Rows[e.RowIndex];
DropDownList _ddl = (DropDownList)_row.FindControl("ddlUpgrade");
SqlParameter _parm = new SqlParameter("#Upgrade", _ddl.SelectedItem.ToString());
}
On the RowUpdating event you can capture the control inside the edit template based on its ID.
GridViewRow row = GridView1.Rows[e.RowIndex];
DropDownList ddl = (DropDownList)row.FindControl("ddlUpgrade");
SqlParameter _parm = new SqlParameter("#Upgrade", ddl.SelectedItem.ToString());
e.Command.Parameters.Add(_parm);
I would add a hidden field outside the GridView:
<asp:HiddenField ID="hdnSelection" value="" runat="server" />
And change the gvClients_RowUpdating method:
protected void gvClients_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow _row = gvClients.Rows[e.RowIndex];
DropDownList _ddl = _row.FindControl("ddlUpgrade") as DropDownList;
if(_ddl != null)
{
hdnSelection.Value = _ddl.SelectedItem.Text;
IAP.Update();//Assuming IAP is the ID of the SqlDataSource
}
}
And my IAP_Updating method should look like this:
protected void IAP_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
SqlParameter _parm = new SqlParameter("#Upgrade", hdnSelection.Value);
e.Command.Parameters.Add(_parm);
}
I did not test the code. You may need to tweak.

How to access control inside parent control? (asp.net c#)

I have page with listview in it. There is label and dropdownlist in listview. I would like to access the text of label from ddlTags_Init() method.
Code:
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1"
DataKeyNames="id_Image" onitemdatabound="ListView1_ItemDataBound">
<ItemTemplate>
<asp:Label ID="TagsLabel" runat="server" Text='<%# Eval("Tags") %>' />
<asp:DropDownList ID="ddlTags" runat="server" OnInit="ddlTags_Init" >
</asp:DropDownList>
</ItemTemplate>
</asp:ListView>
Code behind:
protected void ddlTags_Init(object sender, EventArgs e)
{
DropDownList ddlTags = (DropDownList)sender;
Label lblTag = (Label)ddlTags.Parent.FindControl("TagsLabel");
string text=lblTag.Text;
}
At the moment i am stuck with
Label lblTag = (Label)ddlTags.Parent.FindControl("TagsLabel");
Anyone knows what am i missing?
Thanks, Jim
Assuming that there are more than 1 elements in the listview datasource, why don't you put your code in the ItemDataBound handler? I think that it should work.
Init is too early to get the bind value of Label. In other words, label value hasn't been bind yet.
Instead you might want to consider using ItemDataBound method.
<asp:ListView ID="ListView1" runat="server"
OnItemDataBound="ListView1_ItemDataBound" ...>
....
</asp:ListView>
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var ddlTags = e.Item.FindControl("ddlTags") as DropDownList;
var tagsLabel = e.Item.FindControl("TagsLabel") as Label;
}
}

Avoid Refreshing on Databound Dropdownlist

I am working on a metrics screen that will display several charts based on different groups in a database. Part of it uses a function that hides selected charts until the user clicks to display them.
The problem is this: I'm using a Databind on the dropdownlist, so every time I select a new group, the page refreshes and everything returns to its default state.
My question is this: Is there a way that I can avoid refreshing the page every time I select a new option from the dropdown list? If so, how? If not, is there a better way to create the dropdownlist and attach values to it? If I set AppendDataBoundItems to false, then I always get the selected value as the first item in the list.
Here's my code for the dropdownlist:
<asp:DropDownList ID="MinistryDropdown" OnSelectedIndexChanged="Selection_Change" AutoPostback="true" AppendDataBoundItems="true" runat="server"/>
Then C# code behind it is this:
public void Page_Load(object sender, EventArgs e){
MinistryDropdown.DataSource = CreateDataSource();
MinistryDropdown.DataTextField = "Description";
MinistryDropdown.DataValueField = "Description";
MinistryDropdown.DataBind();
...other code here...
}
ICollection CreateDataSource(){
DataTable Ministries = new DataTable();
Ministries = oDatabase.GetData(#"SELECT DISTINCT B.Description
FROM tblInvolvement AS A LEFT JOIN tblMinistries AS B
ON A.Activity = B.MinistryID");
DataView dv = new DataView(Ministries);
return dv;
}
Try to use the ASP.NET UpdatePanel. Just wrap your DropDownList in it, and it should works. Here is a quick example that I didn't test.
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="MinistryDropdown" OnSelectedIndexChanged="Selection_Change" AutoPostback="true" AppendDataBoundItems="true" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
On a final note, you will soon find out the limits of this solution, and later you might prefer to use Javascript instead.
I think the issue is that you are rebinding the data on Page_Load but you are not checking if !IsPostBack in other words, your code should look like this:
public void Page_Load(object sender, EventArgs e){
if(!IsPostBack)
{
MinistryDropdown.DataSource = CreateDataSource();
MinistryDropdown.DataTextField = "Description";
MinistryDropdown.DataValueField = "Description";
MinistryDropdown.DataBind();
...other code here...
}
}

Rebinding on Postback Based on Selected DropDown Value

Greetings!
I have a DropDownList within a FormView which are bound to XmlDataSources:
<asp:FormView ID="MyFormView" runat="server" DataSourceID="MyXmlDataSource">
<ItemTemplate>
<h1><%# XPath("SomeNode")%></h1>
<asp:Label ID="MyLabel" runat="server" AssociatedControlID="MyDdl" Text='<%# XPath("SomeOtherNode")%>' />
<asp:DropDownList ID="MyDdl"
runat="server"
DataSourceID="MyDdlDataSource"
DataTextField="name"
DataValueField="value"
AutoPostBack="true"
OnSelectedIndexChanged="MyDdl_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:FormView>
<asp:XmlDataSource ID="MyXmlDataSource" runat="server" XPath="Root/MainSection" />
<asp:XmlDataSource ID="MyDdlDataSource" runat="server" XPath="Root/MainSection/Areas/*" />
In the page's codebehind, I have the following OnLoad() method as well as the method for when the select index of the dropdownlist changes:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
string xml = GetMyXml(0); // default value
MyXmlDataSource.Data = xml;
MyDdlDataSource.Data = xml;
}
}
protected void MyDdl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList l_MyDdl = FindControl("MyDdl") as DropDownList;
int myVal;
if (l_MyDdl != null)
if (!Int32.TryParse(l_MyDdl.SelectedItem.Value, out myVal))
myVal = 0;
string xml = GetMyXml(myVal);
MyXmlDataSource.Data = xml;
MyDdlDataSource.Data = xml;
}
When a different value is selected from the dropdown list and SelectedIndexChanged is invoked, I am unable to get the value of the dropdown list (FindControl always returns null) in order to use it to re-bind the datasources. How can I get this value?
Because your dropdownlist is contained within another control it may be that you need a recursive findcontrol.
http://weblogs.asp.net/palermo4/archive/2007/04/13/recursive-findcontrol-t.aspx

Categories