Can't set dropdown list selected item - c#

I have a DropDown list on an ASP.Net web page. I'm trying to set its SelectedValue` on page load. I'm using this page as a reference. Here's my code:
<asp:DropDownList runat="server" ID="ddlType" DataSourceID="sdsType" DataTextField="Name" DataValueField="AssetTypeID" />
<asp:SqlDataSource runat="server" ID="sdsType" ConnectionString='<%$ ConnectionStrings:SystemManagement %>' SelectCommand="SELECT AssetTypeID, [Name] FROM AssetType UNION SELECT 0, '' ORDER BY [Name]" SelectCommandType="Text" />
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
if (Request.QueryString["searchtype"] != null)
{
ddlType.SelectedValue = ddlType.Items.FindByText(Request.QueryString["searchtype"]).Value;
ddlType.SelectedValue = "1";
}
}
else
{
}
}
The first line that sets the SelectedValue will give me a Null Reference Exception and if I inspect the ddlType it has no Items. However, if I comment out the first line setting the SelectedValue and set it using the second line (just hard coding the value) it works. What's going on?

You can use the OnDataBound event to do your current logic
/*Note the addition of "OnDataBound" */
<asp:DropDownList runat="server"
ID="ddlType"
DataSourceID="sdsType"
DataTextField="Name"
DataValueField="AssetTypeID"
OnDataBound="ddlType_DataBound"
/>
<asp:SqlDataSource runat="server" ID="sdsType" ConnectionString='<%$ ConnectionStrings:SystemManagement %>' SelectCommand="SELECT AssetTypeID, [Name] FROM AssetType UNION SELECT 0, '' ORDER BY [Name]" SelectCommandType="Text" />
protected void ddlType_DataBound(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
if (Request.QueryString["searchtype"] != null)
{
ddlType.SelectedValue = ddlType.Items.FindByText(Request.QueryString["searchtype"]).Value;
ddlType.SelectedValue = "1";
}
}
else
{
}
}

When you are trying to set the value for ddlType, the DataSource is not yet loaded to the DropDown. If you check the debugger, the ddlType.Items property will show you that it currently has no items, which explains the NullReference exception.
Try to call ddlType.DataBind() before to ensure that ddlType.Items has the items from the database.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
ddlType.DataBind(); // Load data from DataSource
if (Request.QueryString["searchtype"] != null)
{
ddlType.SelectedValue = ddlType.Items.FindByText(Request.QueryString["searchtype"]).Value;
ddlType.SelectedValue = "1";
}
}
else
{
}
}
Make sure to have the ddlType.DataBind() inside the if(!Page.IsPostBack) condition, to avoid loading the data from the database on every PostBack.

Related

ASP.NET - SelectedValue/Index in Listbox always changing after a postback

I've been wrestling with this problem for days and so far I haven't been able to find an answer that fits this specific issue. Here's the code to load the list in the PageLoad():
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
lstEmprendimientos.DataSource = Emprendimiento.DevolverEmprendimientosConEvaluacionesIncompletas();
lstEmprendimientos.DataValueField = "id";
lstEmprendimientos.DataTextField = "titulo";
lstEmprendimientos.DataBind();
pnlEvaluador.Visible = false;
}
}
The first method loads a list made up of 'Emprendimiento' objects, and on that list's SelectedIndexChanged I call another method to load a list through a method that uses the SelectedValue of the item selected.
My problem is that, no matter what I do, the SelectedIndex is always reset to 0 after a postback, so I can't load the second list using the SelectedValue properly. I've worked with lists for a long while now and I've never had this problem, so it's really baffling. I'd appreciate some help with this.
Here's the code for the whole page:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ddlEmprendimientos.DataSource = Emprendimiento.DevolverEmprendimientosConEvaluacionesIncompletas();
ddlEmprendimientos.DataValueField = "id";
ddlEmprendimientos.DataTextField = "titulo";
ddlEmprendimientos.DataBind();
pnlEvaluador.Visible = false;
}
}
protected void lstEmprendimientos_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void lstEvaluadores_SelectedIndexChanged(object sender, EventArgs e)
{
Evaluador ev = Evaluador.FindByID(lstEvaluadores.SelectedValue);
}
protected void btnAsignarEvaluador_Click(object sender, EventArgs e)
{
Emprendimiento emp = Emprendimiento.FindByID(Convert.ToInt32(ddlEmprendimientos.SelectedValue));
Evaluador ev = Evaluador.FindByID(lstEvaluadores.SelectedValue);
Evaluacion eva = new Evaluacion(emp, ev, 0, "justificacion", DateTime.Now, false);
if (eva != null)
{
if (eva.Insertar())
{
lblFeedback.Text = "Alta exitosa.";
emp.listaEvaluaciones.Add(eva);
lstEvaluadores.DataSource = emp.DevolverListaEvaluadoresQueNoEvaluanEmprendimiento();
lstEvaluadores.DataTextField = "Nombre";
lstEvaluadores.DataValueField = "Email";
lstEvaluadores.DataBind();
pnlEvaluador.Visible = true;
CargarEvaluadores();
}
else
{
lblFeedback.Text = "Error en el ingreso de datos.";
}
}
else
{
lblFeedback.Text = "Error en el ingreso de datos.";
}
}
protected void btnSeleccionarEmp_Click(object sender, EventArgs e)
{
CargarEvaluadores();
}
private void CargarEvaluadores()
{
Emprendimiento emp = Emprendimiento.FindByID(Convert.ToInt32(ddlEmprendimientos.SelectedIndex));
lstEvaluadores.DataSource = emp.DevolverListaEvaluadoresQueNoEvaluanEmprendimiento();
lstEvaluadores.DataTextField = "Nombre";
lstEvaluadores.DataValueField = "Email";
lstEvaluadores.DataBind();
pnlEvaluador.Visible = true;
}
protected void ddlEmprendimientos_SelectedIndexChanged(object sender, EventArgs e)
{
CargarEvaluadores();
}
Page markup:
<%Page Title="" Language="C#" MasterPageFile="~/masterPage.Master" AutoEventWireup="true" CodeBehind="asignarEvaluador.aspx.cs" Inherits="InterfazUsuario.asignarEvaluador">
<asp:DropDownList ID="ddlEmprendimientos" runat="server" OnSelectedIndexChanged="ddlEmprendimientos_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<asp:Button ID="btnSeleccionarEmp" runat="server" OnClick="btnSeleccionarEmp_Click" Text="Seleccionar emprendimiento" Width="195px" />
<br />
<br />
<asp:Panel ID="pnlEvaluador" runat="server">
<asp:ListBox ID="lstEvaluadores" runat="server" OnSelectedIndexChanged="lstEvaluadores_SelectedIndexChanged"></asp:ListBox>
<br />
<br />
<asp:Button ID="btnAsignarEvaluador" runat="server" OnClick="btnAsignarEvaluador_Click" Text="Asignar evaluador" Width="135px" />
<br />
<br />
<asp:Label ID="lblFeedback" runat="server"></asp:Label>
<br />
</asp:Panel>
You need to change your DropDownList and ListBox controls to AutoPostback
DropDownList
<asp:DropDownList ID="ddlEmprendimientos" runat="server"
OnSelectedIndexChanged="ddlEmprendimientos_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
ListBox
<asp:ListBox ID="lstEvaluadores" runat="server"
OnSelectedIndexChanged="lstEvaluadores_SelectedIndexChanged"
AutoPostBack="True">
</asp:ListBox>
AutoPostBack:
Set this property to true if the server needs to capture the selection
as soon as it is made. For example, other controls on the Web page can
be automatically filled depending on the user's selection from a list
control.
This property can be used to allow automatic population of other controls on > the Web page based on a user's selection from a list.
The value of this property is stored in view state.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.autopostback(v=vs.110).aspx
I found the problem after checking everything out again.
The DataValueField in the list was 'id', and the id field in the 'Emprendimiento' class wasn't defined, so it was always returning a null int (0). Thank you kindly for the help, it was just a dumb mistake in the end.

Cannot get rid of duplicate values in populated listbox

I have tried to look at other solutions, but I cannot seem to find the answer. I am currently using a listbox to show data from the database using a sqldatasource. It is populated after I select a value from a dropdownlist before hand. When using the listbox I want to save the selected items after I click it so I set AppendDataBoundItems to true. It seems when I set it to false, I no longer get duplicates values, however then I cannot keep the selected value of the listbox after binding. I have also tried to enable/disable the view state but no luck. I am positive that I am using the DISTINCT keyword in my query but still no luck.
ASP.Net
<asp:DropDownList ID="ProgramDropDownList" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="Program" DataValueField="ProgramID">
</asp:DropDownList>
<asp:DropDownList ID="ReportPeriodDropDownList" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource2" DataTextField="ReportLabel" DataValueField="DataCollectionPeriodID" Height="21px" Width="172px">
</asp:DropDownList>
<div style="width:400px; height:auto; overflow:auto; text-align: center; margin-left: auto; margin-right: auto; left: 0; right: 0">
<asp:ListBox ID="FormSectionListBox" DataSourceID="FormSectionDataSource" runat="server" AutoPostBack="True" DataTextField="FormSection" DataValueField="FormSectionID" AppendDataBoundItems="True" EnableViewState="False">
</asp:ListBox>
</div>
<asp:SqlDataSource ID="FormSectionDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:SmartFormConnection %>" SelectCommand="SELECT DISTINCT FormSection, FormSectionID FROM Core.FormSection_Lkup
where formsectionid IN (select formsectionid from core.form_section_subsection_item_rel where datacollectionperiodid = #datacollectionperiodid) order by FormSection">
<SelectParameters>
<asp:ControlParameter ControlID="ReportPeriodDropDownList" Name="datacollectionperiodid" PropertyName="SelectedValue" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
_connection = DataAccess.SelfRef().GetConnection();
string eTarget = Request.Params["__EVENTTARGET"];
if (string.IsNullOrEmpty(eTarget)) return;
var list = InstructionDropDown.SelectedValue;
switch (list)
{
case "Form Section":
FormSectionListBox.DataSourceID = "FormSectionDataSource";
FormSectionListView.DataBind();
RenderView(FormSectionListView, "hidden"); // hide listview on page load
break;
}
}
I guess that you just have to ensure that the list is not filled on every postback:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// do what you need on the initial load
}
}
If you need to handle the DropDownList selection use the appropriate events. In this case the SelectedIndexChanged event.
protected void InstructionDropDown_SelectedIndexChanged(Object sender, EventArgs e)
{
var list = InstructionDropDown.SelectedValue;
switch (list)
{
case "Form Section":
FormSectionListBox.DataSourceID = "FormSectionDataSource";
FormSectionListView.DataBind();
RenderView(FormSectionListView, "hidden"); // hide listview on page load
break;
}
}
}
I was able to find a work around. I set the AppendDataBoundItems to false. And used the SelectedIndexChanged Property to save the selected index after Binding.
protected void FormSectionListBoxSelectedIndexChanged(object sender, EventArgs e)
{
var item = FormSectionListBox.SelectedIndex;
FormSectionListBox.DataSourceID = "FormSectionDataSource";
FormSectionListView.DataBind();
FormSectionListBox.SelectedIndex = item;
}

Display different Gridviews with a Dropdownlist onchange

I want to show different Gridviews when I select values from a dropdownlist.I use Visible="False" property to gridviews and I want to show only one on every value updated.
Example: when I select the Value "Points" I want to show GridView1 and when I select Names I want to show "GridView2". This is my ASP:
<asp:DropDownList ID="Stats_Ddl" runat="server" AutoPostBack="True" OnSelectedIndexChanged="Stats_Ddl_IndexChanged" >
<asp:ListItem>POINTS</asp:ListItem>
<asp:ListItem>NAMES</asp:ListItem>
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" Visible="False"> blahblahblah1</asp:GridView>
<asp:GridView ID="GridView2" runat="server" Visible="False">blahblahblah12</asp:GridView>
and c# is:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Stats_Ddl_IndexChanged(object sender, EventArgs e)
{
}
Any suggestions for c# code? thanks...
Hi inside event SelectedIndexChanged
you should put for example
If(Ddl.SelectedValue == "1"){
GridView1.Visible = true;
GridView2.Visible = false;
}else{
GridView1.Visible = false;
GridView2.Visible = true;
}
i see that you have a ListItem don't forget give to a value to property "Value" for example
Point = 1
Name = 2
You can use SelectedItem.Text property of DropDownList to branch
protected void Stats_Ddl_IndexChanged(object sender, EventArgs e)
{
if(Stats_Ddl.SelectedItem.Text == "POINTS")
GridView1.Visible = true;
else
if(Stats_Ddl.SelectedItem.Text == "NAMES")
GridView2.Visible = true;
}

DropDown list not firing change event when it is altered

I have a page with a dropdownlist and a button on it. The initial selection on the dropdown is an empty string. I do not want this submitted to the server so I disable the button. I then want to enable the button if any other selection is made on the dropdown. However my ddlBusinessUnit_SelectedIndexChanged method is never hit when I make changes in the dropdown list.
html:
<asp:DropDownList ID="ddlBusinessUnit" EnableViewState="true" runat="server"
OnSelectedIndexChanged="ddlBusinessUnit_SelectedIndexChanged" />
code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dsDate.Date = DateTime.Today;
PopulateBusinessUnits();
StatusMessages.Visible = false;
}
bGetFiles.Enabled = false;
}
public void ddlBusinessUnit_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlBusinessUnit.SelectedItem.Text != "")
bGetFiles.Enabled = true;
}
Set AutoPostBack="true" for your dropdown.
<asp:DropDownList ID="ddlBusinessUnit" EnableViewState="true" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddlBusinessUnit_SelectedIndexChanged" />
you're missing AutoPostBack="true" on your asp dropdown control

how to filtering Gridview data

Gridview contains 100 customer, each page 10 customer, how to filter Alphabatically;
If an user clicks A, then list out all customer names that starts with A
Please help.
If you're using an SqlDataSource, you can specify a parameter in the SelectCommand, e.g.
SelectCommand="SELECT * FROM [Genre] WHERE [Name] LIKE #FirstLetter+'%'"
You will have to add the parameter within the , e.g.
<SelectParameters>
<asp:Parameter Name="FirstLetter" Type="String" />
</SelectParameters>
In your code behind, you can set the value of the parameter, e.g.
SqlDataSource1.SelectParameters["FirstLetter"].DefaultValue = filterletter;
The Faster and jQuery Approach is mentioned in this link
$(document).ready(function() {
$('#<%=lblNoRecords.ClientID%>').css('display','none');
$('.links').click(function(e)
{
$('#<%=lblNoRecords.ClientID%>').css('display','none');
var lnkText = $(this).text().toLowerCase();
var iCounter = 0;
$("#<%=gdRows.ClientID%> tr:has(td)").each(function() {
var cell = $(this).find("td:eq(1)").text().toLowerCase();
if(lnkText != 'all')
{
if(cell.indexOf(lnkText) != 0)
{
$(this).css('display','none');
}
else
{
$(this).css('display','');
iCounter++;
}
}
else
{
$(this).css('display','');
iCounter++;
}
});
if(iCounter == 0)
{
$('#<%=lblNoRecords.ClientID%>').css('display','');
}
e.preventDefault();
});
});
Approach #1
ASPX markup:
<asp:Repeater ID="rptAlpha" runat="server" OnItemCommand="rptAlpha_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lbAlpha" runat="server"
CommandArgument='<%# Container.DataItem.ToString() %>'><%#Container.DataItem.ToString() %></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1">
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
OldValuesParameterFormatString="original_{0}"
OnSelecting="ObjectDataSource1_Selecting" SelectMethod="Load" TypeName="Your.TypeName.Here">
<SelectParameters>
<asp:Parameter Name="Filter" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
C# code
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
BindAlphaRepeater();
}
private void BindAlphaRepeater()
{
string[] alphabet = {"a", "b", "c", "d", "e" };
rptAlpha.DataSource = alphabet;
rptAlpha.DataBind();
}
protected void rptAlpha_ItemCommand(object source, RepeaterCommandEventArgs e)
{
string filterleter = e.CommandArgument as string;
if (filterleter == null)
return;
ViewState["filterletter"] = filterleter;
GridView1.DataBind();
}
protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
// This is designed to return null, you might want to change it to a default value
e.InputParameters["Filter"] = ViewState["filterletter"] as string
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Paging click");
GridView1.DataBind();
}
Explanation:
User a repeater to bind the alphabets and use OnItemCommand of that Repeatet to fetch data and bind the grid view based on selected alphabet.
Approach #2
You can have 26 buttons on top of gridview + one button for All on top of the gridview.
For all 26 buttons you can have common method like buttonAPLHA_Click and based on sender.tag you can filter the data of the gridview.
e.g inside your buttonAPLHA_Click you can have.
GridView.datasource = GetDataByAplha(Sender.Tag.Tostring());
Hope you get what I want to explain.
use this sample query..
string query = "select from tbl_name where name like '%" + dropdownlist.SelectedValue + "'";

Categories