Why asp:DropDownList does not respond to code-behind - c#

I have the following ASP drop-down:
<asp:DropDownList ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
<asp:ListItem Text="BY LOCATION" Value="1" />
<asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>
<br /><br />
<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
I am trying to make it interactive where if the first select option is changed the second will change as well based on the selection from the first select option.
My C# code looks like this:
public partial class test : System.Web.UI.Page
{
String cString;
SqlConnection Conn;
protected void Page_Load(object sender, EventArgs e) {
PopulatePhysician();
//PopulateSpecialty();
//PopulateLocation();
}
public void PopulatePhysician() {
SqlCommand cmd = new SqlCommand("getPhysicians", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
//cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Physician's Name";
Item.Value = "0";
//Item.Selected = True
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void PopulateSpecialty() {
SqlCommand cmd = new SqlCommand("getSpecialties", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Specialty";
Item.Value = "0";
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void PopulateLocation() {
SqlCommand cmd = new SqlCommand("getLocations", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Location";
Item.Value = "0";
ddlDrillDown.Items.Insert(0, Item);
cmd.Connection.Close();
cmd.Connection.Dispose();
//}
}
public void ddlMain_SelectedIndexChanged(object sender, System.EventArgs e) {
switch(ddlMain.SelectedItem.Value) {
case "0":
PopulatePhysician();
break;
case "1":
PopulateLocation();
break;
case "2":
PopulateSpecialty();
break;
}
}
}
When the page first loads, PopulatePhysician(); works great by populating the select option. But when I call the SelectedIndexChanged() function, nothing happens.
How can I resolve it? Is the case statement correct?

You haven't added any delegates to the SelectedIndexChanged event.
Add OnSelectedIndexChanged to the parameters in the asp:DropDownList tag, like so:
<asp:DropDownList ClientIDMode="Static" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true" >
EDIT
I just noticed you're actually missing the AutoPostBack event as well - it should be set to true, as updating the selection without submitting the form will not fire a postback event, unless AutoPostBack is set to true.

It needs AutoPostback=true on the Dropdown list
<asp:DropDownList AutoPostback="true" ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">

Remove the If (!IsPostBack) clause from your functions. Check for that in page load, but not in each individual function.

Related

asp:gridview filter using listbox cannot make multiple selection

I have this asp:gridview in which I show data using mySql stored procedure. I have this listbox named ddlstatus which I use to filter the data. I use viewstate to show data that are selected from the listbox. The problem is I want to make multiple selection on this listbox and show data for each selection made on it, but when it only shows data for the initial selection.
The below is the client side code:
<asp:Label ID="lblstat" Text="status" Visible="false" runat="server"></asp:Label>
<asp:ListBox ID="ddlstatus" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox>
<asp:GridView ID="gdvTM" runat="server" ControlStyle-Width="100%" AutoGenerateColumns="False" DataKeyNames="ID" OnRowDeleting="gdvTM_RowDeleting" PageSize="5" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc">
<Columns >
<asp:TemplateField HeaderText="Current Status">
<ItemTemplate >
<asp:Label ID="lblcstat" runat="server" Text='<%# Eval("status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The below is the server side code:
private void BindDropDownList()
{
PopulateDropDown(ddlstatus, lblstat.Text);
}
private void PopulateDropDown(ListBox ddl, string columnName)
{
ddl.Items.Clear();
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetTMData");
cmd.CommandType = CommandType.StoredProcedure;
string statusVal = null;
if (ViewState["stat"] != null && ViewState["stat"].ToString() != "0")
{
statusVal = ViewState["stat"].ToString();
}
cmd.Parameters.AddWithValue("statusVal", statusVal);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["stat"] != null ? (string)ViewState["stat"] : string.Empty, ddlstatus);
}
private void setDropdownselectedItem(string selectedvalue, ListBox ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
ListBox dropdown = (ListBox)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlstatus":
ViewState["stat"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
string username = uName.Text;
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT (" + columnName + ") FROM approved WHERE tm = #tm AND " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#tm", username);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Below is the MySql stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetTMData`(in statusVal varchar(45))
BEGIN
SELECT *
FROM approved
WHERE (statusVal IS NULL
OR status = statusVal)
order by date desc;
END
How can I make this happen? Thanks in advance.
Please make listbox multiple
<asp:ListBox id="ListBox1"
Rows="6"
Width="100px"
**SelectionMode="Multiple"**
runat="server">
<asp:ListItem Selected="True">Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
Then in server side
void SubmitBtn_Click(Object sender, EventArgs e)
{
Message.Text = "You chose: <br />";
// Iterate through the Items collection of the ListBox and
// display the selected items.
foreach (ListItem item in ListBox1.Items)
{
if(item.Selected)
{
Message.Text += item.Text + "<br />";
}
}
}
First of all, auto post back not allow you to select multiple items because upto select second item, the postback already happens by first selected item so,
You have to set AutoPostBack="false" for your list box,
<asp:ListBox ID="ddlstatus" runat="server" AutoPostBack="false" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox>
For collecting multiple selected items we simply choose button for instance, you can collect those items wherever you want,
Then add one button that will call below code
<asp:Button ID="button1" runat="server" OnClick="button1_Click" Text="Click"/>
On above button event handler add below code,
protected void button1_Click(object sender, EventArgs e)
{
var selectedNames = ddlstatus.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => i.Value)
.ToList();
string selectedValue = string.Join("','", selectedNames);
selectedValue = "'" + selectedValue + "'";
ViewState["stat"] = selectedValue;
}
Then the comma separated items in your ViewState will be used in your stored procedure parameter
string statusVal = null;
if (ViewState["stat"] != null && ViewState["stat"].ToString() != "0")
{
statusVal = ViewState["stat"].ToString();
}
cmd.Parameters.AddWithValue("statusVal", statusVal); //<= Now this string variable contains comma separated list box items values.
If you populate your list box on Page_Load then make sure that you should populate it into !Page.IsPostBack like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Populate your list box here
}
}
And your SP is
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetTMData1`(in statusVal varchar(255))
BEGIN
IF statusVal = '\'\'' THEN
select * from approved;
ELSE
SET #sql = CONCAT('SELECT * FROM approved WHERE status IN (', statusVal, ')');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF ;
END
If you select multiple items from the dropdown then your SP's parameter data look like '\'apple\',\'banana\''. If not then it look like '\''.
There's a few issues that I could spot that may need to be addressed,
Ensure that the method BindDropDownList is only called on a non postback (page refresh), because your method PopulateDropDown is clearing the items on the list which means that viewstate cannot be restored in a postback, hence the probable reason why only one item is being selected.
I'm not 100% of the table schema, but the SQL provided does not seem to be able to query by more than one status properly, you should probably send a comma separated list of values, and in SQL turn them into a temp table so that you effectively search for items with multiple status (you should probably create a new question for this).
Do not use SelectedItem for multiple selections, instead you need to iterate your list items for those that are selected, and you don't need to use ViewState to pass it along (you probably did because of point 1. above). For example you could replace your method BindGrid and DropDownChange with:
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetTMData");
cmd.CommandType = CommandType.StoredProcedure;
string statusVal = null;
foreach (ListItem item in ddlstatus.Items)
{
if(item.Selected)
{
if(statusVal.length > 0)
statusVal += ",";
statusVal += item.Value;
}
}
cmd.Parameters.AddWithValue("statusVal", statusVal);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
gdvTM.DataBind();
}
protected void DropDownChange(object sender, EventArgs e)
{
this.BindGrid();
}

Cascading dropdown not populating

I have been following the following example to create some cascading dropdowns in a web application. The example does not use jquery and I would like to stick with this for now.
https://www.aspsnippets.com/Articles/Populate-Cascading-DropDownList-from-Database-in-ASPNet-Example.aspx
I am having trouble getting my second dropdown to populate a list using the result from the first. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CategorySelect.Items.Clear();
CategorySelect.Items.Add(new ListItem("--Select Activity--", ""));
CategorySelect.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["iSAMSConnectionString"].ConnectionString;
String strQuery = "select TblActivityManagerFolderID, txtName from dbo.TblActivityManagerFolder";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
CategorySelect.DataSource = cmd.ExecuteReader();
CategorySelect.DataTextField = "txtName";
CategorySelect.DataValueField = "TblActivityManagerFolderID";
CategorySelect.DataBind();
}
finally
{
con.Close();
con.Dispose();
}
}
}
protected void ActivitySelect_SelectedIndexChanged(object sender, EventArgs e)
{
ActivitySelect.Items.Clear();
ActivitySelect.Items.Add(new ListItem("--Select Activity--", ""));
ActivitySelect.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["iSAMSConnectionString"].ConnectionString;
String strQuery = "select txtName, TblActivityManagerGroupID from dbo.TblActivityManagerGroup " +
"where intFolder=#txtName";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#txtName",
CategorySelect.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ActivitySelect.DataSource = cmd.ExecuteReader();
ActivitySelect.DataTextField = "txtName";
ActivitySelect.DataValueField = "TblActivityManagerGroupID";
ActivitySelect.DataBind();
if (ActivitySelect.Items.Count > 1)
{
ActivitySelect.Enabled = true;
}
else
{
ActivitySelect.Enabled = false;
}
}
finally
{
con.Close();
con.Dispose();
}
}
I am using 2 tables.
TblActivityManagerFolder where I am using 2 fields - TblActivityManagerFolderID and txtName
TblActivityManagerGroup where I am using 2 fields - intFolder (which joins to TblActivityManagerFolderID) and txtName
My first drop down populates exactly as expected, but when I make a selection nothing at all happens in the 2nd dropdown.
Additional Code:
<asp:SqlDataSource ID="iSAMS" runat="server" ConnectionString="<%$ ConnectionStrings:iSAMSConnectionString %>"
SelectCommand="SELECT [blnActive], [TblActivityManagerFolderID], [txtName] FROM [TblActivityManagerFolder] WHERE ([intActivity] = #intActivity)">
<SelectParameters>
<asp:Parameter DefaultValue="34" Name="intActivity" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</div>
<div class="auto-style18">
<asp:DropDownList ID="CategorySelect" runat="server" DataTextField="txtName" DataValueField="TblActivityManagerFolderID"
OnSelectedIndexChanged="ActivitySelect_SelectedIndexChanged" CssClass="newStyle1">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="CategorySelect"
ErrorMessage="Please select your answer" style="text-align: left; font-weight: 700; color: #FF0000; font-size: medium;">!</asp:RequiredFieldValidator>
</div>
<br />
<div class="auto-style19">
<div class="auto-style20">
Please select the activity undertaken from the pick list:
<asp:DropDownList ID="ActivitySelect" runat="server" DataSourceID="iSAMSActivity" DataTextField="txtName" DataValueField="TblActivityManagerGroupId" CssClass="newStyle1" OnSelectedIndexChanged="ActivitySelect_SelectedIndexChanged">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ActivitySelect"
ErrorMessage="Please select your answer" style="text-align: left; font-weight: 700; color: #FF0000; font-size: medium;">!</asp:RequiredFieldValidator>
<asp:SqlDataSource ID="iSAMSActivity" runat="server" ConnectionString="<%$ ConnectionStrings:iSAMSConnectionString %>" SelectCommand="SELECT [txtName], [intActivity], [intFolder], [TblActivityManagerGroupId] FROM [TblActivityManagerGroup] WHERE ([intFolder] = #intFolder)">
<SelectParameters>
<asp:ControlParameter ControlID="CategorySelect" Name="intFolder" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
I am also posting back the results so I can see if this is working using:
protected void Button1_Click(object sender, EventArgs e)
{
var activity = CategorySelect.DataTextField;
var CoCActivity = ActivitySelect.DataTextField;
var OtherSkills = SkillsTextBox.Text;
var ExtraDev = DevTextBox.Text;
var OtherActivities = OtherActivitiesTextBox.Text;
OutputLabel.Text = activity + "<br/>" + CoCActivity + "<br/>" + OtherSkills + "<br/>" + ExtraDev + "<br/>" + OtherActivities;
}
When it is posting back, it is producing an integer rather than the label in the dropdown list. Can this be changed so it post backs the actual text?
Set the AutoPostBack property of the DropdownList to True. If you dont set it, the event would be only be triggered server side when other events force a postback (a button click or similar)

Give the gridview columns a alias name in C#

I have a GridView which is not DataSource bound. At run time this GridView shows some rows at run time. There is a requirement in which user should be able to change the column header text at run time. So i thought of to implement in this way -
User will double click [or single click] on column header and a text box will be visible to user, where user will enter the new text and as soon as user leaves the text box, new column header text will be set as HeaderText property of the column. Can this achieved? can anyone share the sample code to achieve the same? I will be highly obliged to you. Any help will be appreciable.
This is my grid
<asp:GridView ID="GdvTestData" runat="server"
class="table table-striped table-responsive table-hover"
onrowdatabound="gv_RowDataBound"
PageSize="100" OnSelectedIndexChanged="GdvTestData_SelectedIndexChanged">
<FooterStyle BorderStyle="Solid" />
</asp:GridView>
Here is the thing that you can do to bind alias with the column
Below is aspx code
<asp:DropDownList runat="server" ID="ddlQuery">
<asp:ListItem Text="Query1" Value="1" Selected="True"></asp:ListItem>
<asp:ListItem Text="Query2" Value="2"></asp:ListItem>
<asp:ListItem Text="Query3" Value="3"></asp:ListItem>
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtAlias"></asp:TextBox>
<asp:Button runat="server" ID="btnGetData" Text="GetData" OnClick="btnGetData_Click" />
<asp:GridView runat="server" ID="gcData"></asp:GridView>
And code to bind data to grid in cs is below
protected void btnGetData_Click(object sender, EventArgs e)
{
GetData();
}
private void GetData()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Connection String";
string Query = string.Empty;
if (ddlQuery.SelectedValue == "1")
Query = "SELECT * FROM Table1";
else if (ddlQuery.SelectedValue == "2")
Query = "SELECT * FROM Table2";
else if (ddlQuery.SelectedValue == "3")
Query = "SELECT * FROM Table3";
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = Query;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DataTable dtFinal = new DataTable();
foreach (DataColumn cln in dt.Columns)
{
dtFinal.Columns.Add(cln.ColumnName + " " + txtAlias.Text, cln.DataType);
}
foreach (DataRow row in dt.Rows)
{
DataRow dr = dtFinal.NewRow();
for (int i = 0; i < dtFinal.Columns.Count; i++)
{
dr[i] = row[i];
}
dtFinal.Rows.Add(dr);
}
gcData.DataSource = dtFinal;
gcData.DataBind();
}
catch (Exception)
{
throw;
}
}

Show Table when SelectedValue of DropDownList is true C#

I want to show a table when a SelectedValue of my DropDownList ddlKlasse is true. I'm using asp.net empty web forms with a masterpage.
The idea is:
when ddlKlasse.SelectedValue = "2" table tblDubbelTwee must be shown
when ddlKlasse.SelectedValue = "5" table tblVierMet must be shown
when ddlKlasse.SelectedValue = "9" table tblAchtMet must be shown
I get the values in my dropdownlist from my database.
The code I have now is:
In my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
BindDropDownListKlasse();
BindDropDownListVereniging();
if (!Page.IsPostBack)
{
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
}
}
For binding the dropdown:
private void BindDropDownListKlasse()
{
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "SELECT DISTINCT AantalDeelnemers, Naam FROM Klasse;";
com.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
ddlKlasse.DataSource = dt;
ddlKlasse.DataValueField = "AantalDeelnemers";
ddlKlasse.DataTextField = "Naam";
ddlKlasse.DataBind();
conn.Close();
//Adding "Kies de klasse" optie in dropdownlist voor validatie
ddlKlasse.Items.Insert(0, new ListItem("Kies de klasse", "0"));
}
}
}
catch
{
}
}
For showing the tables:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
ListItem selectedListItemDubbelTwee = ddlKlasse.Items.FindByValue("2");
if (selectedListItemDubbelTwee != null)
{
selectedListItemDubbelTwee.Selected = true;
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemVierMet = ddlKlasse.Items.FindByValue("5");
if (selectedListItemVierMet != null)
{
selectedListItemVierMet.Selected = true;
tblVierMet.Visible = true;
tblDubbelTwee.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemAchtMet = ddlKlasse.Items.FindByValue("9");
if (selectedListItemAchtMet != null)
{
selectedListItemAchtMet.Selected = true;
tblAchtMet.Visible = true;
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
};
}
My DropDownList:
<div class="form-inline">
<div class="form-group">
<asp:DropDownList ID="ddlKlasse" class="form-control" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlKlasse_SelectedIndexChanged"></asp:DropDownList>
</div>
</div>
One of my tables:
<asp:Table ID="tblDubbelTwee" runat="server" class="table">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Naam</asp:TableHeaderCell>
<asp:TableHeaderCell>Email</asp:TableHeaderCell>
<asp:TableHeaderCell>Lidmaatschapsnr</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
But when I run my project and select a field in my DropDownList it gives the error: System.Web.HttpException: Selecting multiple items in a DropDownList is not allowed.
Can you please help me to solve this problem?
Your current handler for DDL index change is doing something very different from what you have described. It basically checks if the list item exists in the ddl list (no matter selected or not) and then tries to select it. Since all of 3 items exist, you are effectively trying to select 3 items, which is not allowed.
What you might be looking for is a switch by selected value:
switch (ddlKlasse.SelectValue)
{
case "2":
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
break;
case "5": //similar here
case "9": //similar here
default:
// exception or something
}
refere this code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindgrid();
}
}
void bindgrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("select DISTINCT Class from addmitionform1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlclass.DataSource = ds;
ddlclass.DataTextField = "Class";
ddlclass.DataValueField = "Class";
ddlclass.DataBind();
ddlclass.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
string id = (ddlclass.SelectedValue.ToString());
con.Close();
SqlDataAdapter da1 = new SqlDataAdapter("Select id,FirstName from addmitionform1 where Class= '" + id + "'", con);
//SqlDataAdapter da1 = new SqlDataAdapter("Select * from addmitionform1 ", con);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView1.DataSource = ds1;
GridView1.DataBind();
}
First move BindDropDownListKlasse() and BindDropDownListVereniging() inside if (!IsPostBack), as HarveySpecter suggested.
And change ddlKlasse_SelectedIndexChanged() to:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
bool showDubbelTwee = false, showVierMet = false, showAchtMet = false;
switch (ddlKlasse.SelectedValue)
{
case "2":
showDubbelTwee = true;
break;
case "5":
showVierMet = true;
break;
case "9":
showAchtMet = true;
break;
}
tblAchtMet.Visible = showVierMet;
tblDubbelTwee.Visible = showDubbelTwee;
tblVierMet.Visible = showVierMet;
}
What you are doing now in ddlKlasse_SelectedIndexChanged() is check for each value if it's present in the dropdown, and if present select it and show the respective table.
Instead, you need to check which value is selected and show the respective table.

Change gridview header text when i choose dropdownlist

I have some doubt
This is my coding for aspx page and .cs page
How can I achieve the following
If i select February the header text assigned January value and i select march then assign February value...Could you please help me find a solution for it
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" >
<Columns>
<asp:TemplateField HeaderText="8-14">
<ItemTemplate>
<asp:TextBox ID="TxtWeek2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In .CS page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Add("Select");
DropDownList1.Items.Add("January");
DropDownList1.Items.Add("February");
DropDownList1.Items.Add("March");
DropDownList1.Items.Add("April");
DropDownList1.Items.Add("May");
SqlConnection cn = new SqlConnection("Data Source=192.169.10.22;Initial Catalog=SHRICITYUNO;User ID=uno;Password=uno");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd = new SqlCommand("SELECT Week1 FROM Finman_FundPlan", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = DropDownList1.SelectedItem.Text.ToString();
if (DropDownList1.SelectedItem.Text == "January")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
else if (DropDownList1.SelectedItem.Text == "February")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "-";
}
else if (DropDownList1.SelectedItem.Text == "March")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
else if (DropDownList1.SelectedItem.Text == "April")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-30";
}
else if (DropDownList1.SelectedItem.Text == "May")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
}
you can do it using Javascript at client side.
if you observe the grid view then you can notice that row[0] is the header row for gridview.
now you can check decide the which cell test you have to change.
see the following javascript function to accomplish your task
<script language="Javascript">
function ChangeHeaderText()
{
var gridObject = document.getElementById("Gridview1");
gridObject.rows[0].cells[0].innerText = 'NewHeader Text';
return false;
}
</script>
//call above function on 'onchange' event of dropdownlist
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onchange = "return ChangeHeaderText()"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Try this It will work......

Categories