Dropdownlist SelectIndexChanged Not firing C# - c#

I don't get on well with post back/DDL's.. yes I have used autopostback = true!
Below, I am trying to get the selected index changed... to fire on budgetDDL1 however, whatever I try it doesn't!
I'm binding data from a DB to the ddl...
I've tried binding/adding the ddl to the table inside/outside the post backs and enabling/disabling the view states etc.. none of this works.. there must be an easy answer?!
In what order do I need to create/bind the dropdowns for the index changed method to fire an explanation would be useful too!
DropDownList budgetDDL1 = new DropDownList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string QueryString = "SELECT [BudgetCode], [Department], CONCAT([BudgetCode],' - ', [Department]) AS 'textvalue' FROM [tblBudget]";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(QueryString, myConnection))
{
myConnection.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);
budgetDDL1.SelectedIndex = 0;
budgetDDL1.DataSource = dt;
budgetDDL1.DataTextField = "textvalue";
budgetDDL1.DataValueField = "BudgetCode";
budgetDDL1.AutoPostBack = true;
budgetDDL1.SelectedIndexChanged += budgetDDL1_SelectedIndexChanged;
budgetDDL1.DataBind();
}
}
}
table1.Controls.Add(budgetDDL1);
}
protected void budgetDDL1_SelectedIndexChanged(object sender, EventArgs e)
{ *I have a breakpoint here which doesn't fire*
string msg = budgetDDL1.SelectedItem.Text;
ScriptManager.RegisterClientScriptBlock(sender as System.Web.UI.Control, this.GetType(), "alert", "alert('" + msg + "')", true);
}
view:
<body>
<form runat="server">
<table>
<tr>
<td id="table1" runat="server">
</td>
</tr>
</table>
</form>
</body>

Place auto post back code out side of the !IsPostback
DropDownList budgetDDL1 = new DropDownList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string QueryString = "SELECT [BudgetCode], [Department], CONCAT([BudgetCode],' - ', [Department]) AS 'textvalue' FROM [tblBudget]";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(QueryString, myConnection))
{
myConnection.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);
budgetDDL1.SelectedIndex = 0;
budgetDDL1.DataSource = dt;
budgetDDL1.DataTextField = "textvalue";
budgetDDL1.DataValueField = "BudgetCode";
}
}
}
budgetDDL1.AutoPostBack = true;
budgetDDL1.SelectedIndexChanged += budgetDDL1_SelectedIndexChanged;
budgetDDL1.DataBind();
table1.Controls.Add(budgetDDL1);
}

Dynamic controls should be added on Init. After OnLoad finishes executing ASP.NET starts processing control's events and values. You can read/write their properties on or after Load.
Suggest you to check the place where you have created DropDownList.
Answer: because you have created DropDownList after the events have been processed.
Have a look here: https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx

Related

How to redirect from the values of DropDownList using SQL Server?

I'm having a problem with redirecting the page to the another one according to the selectedvalue from dropdownlist.
I can list categories in the dropdownlist using SQL Server.
namespace Deneme
{
public class Baglanti
{
public SqlConnection Baglanma()
{
//integrated security windows auth için.
SqlConnection baglan = new SqlConnection("Server=DESKTOP-IB3QGLL;Database=Sports;Integrated Security = True");
baglan.Open();
SqlConnection.ClearPool(baglan);
SqlConnection.ClearAllPools();
return (baglan);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand komut2 = new SqlCommand("SELECT clubid,club_name FROM kulupler", baglan.Baglanma());
SqlDataReader reader = komut2.ExecuteReader();
baglan.Baglanma();
DDLProduct.DataSource = reader;
DDLProduct.DataValueField = "clubid";
DDLProduct.DataTextField = "club_name";
DDLProduct.DataBind();
}
protected void BtnGonder_Click(object sender, EventArgs e)
{
Response.Redirect("Category.aspx?ID="+DDLProduct.SelectedValue);
}
Product:
<asp:DropDownList ID="DDLProduct" runat="server">
</asp:DropDownList>
<asp:button id="BtnGonder" runat="server" text="Gönder" OnClick="BtnGonder_Click">
</asp:button>
I can list all the categories in the dropdown list. When I click the button it's always goes to Category.aspx?ID=1 which is the value of the first element of the dropdownlist.
try this
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtblItemList = new DataTable();
using (SqlConnection conn = DataExecutor.GetSqlConnection()){
conn.Open();
SqlCommand komut2 = new SqlCommand("SELECT clubid,club_name FROM
kulupler", conn);
//SqlDataReader reader = komut2.ExecuteReader();
using(SqlDataReader reader = DataExecutor.GetSqlDataReader(komut2,
CommandBehavior.Default))
{
dtblItemList.Load(reader);
}
}
DDLProduct.DataSource = dtblItemList;
DDLProduct.DataValueField = "clubid";
DDLProduct.DataTextField = "club_name";
DDLProduct.DataBind();
}

label does not behave properly

I am devleoping a online airline reservation system in which i have two dropdownlists to select source and destinations and a label .this label will show " there are no flights" if there are no matching routes retrieved from the database (in this case its sqlserver 2008).i have written the following code which tries to do so, but when i postback or refresh the page the label with " there are no flights" is till visible.what is wrong with my code please anyone help me with that.
public partial class Dropdndemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con=new SqlConnection("Data Source=KUNDAN-PC\\SQLEXPRESS;Initial Catalog=Ars2.1.2;Integrated Security=True");
//string Sqlcmnd="select Source from Ars2.1.2.dbo.Scheduling";
con.Open();
if (!Page.IsPostBack)
{
SqlCommand com = new SqlCommand("select distinct Source from Schedulings", con);
SqlCommand comn=new SqlCommand("select distinct Destination from Schedulings", con);
//SqlDataReader readr;
DropDownList1.DataSource = com.ExecuteReader();
DropDownList1.DataTextField = "Source";
// DropDownList1.DataTextField = "Destination";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "select Source");
con.Close();
con.Open();
DropDownList2.DataSource = comn.ExecuteReader();
DropDownList2.DataTextField = "Destination";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, "select Destination");
con.Close();
}
//con.Close();
// DropDownList1.DataBind();
//con.Close();
if (IsPostBack)
Label3.Text = "";
//Label1.Visible = false;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// string Source = DropDownList1.SelectedValue.ToString();
// Label1.Text = Source;
}
protected void Button1_Click(object sender, EventArgs e)
{
string src = DropDownList1.SelectedItem.ToString();
string desti = DropDownList2.SelectedItem.ToString();
if ((src == desti) && IsPostBack)
{
Label1.Text = "Source And Destination cant be same!";
}
SqlConnection lop = new SqlConnection("Data Source=KUNDAN-PC\\SQLEXPRESS;Initial Catalog=Ars2.1.2;Integrated Security=True");
lop.Open();
SqlCommand cmd = new SqlCommand("select * from Schedulings where Source=#Source and Destination=#Destination", lop);
cmd.Parameters.AddWithValue("Source", DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("Destination", DropDownList2.SelectedItem.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 0)
{
Label3.Text = "No planes available in this route!!!";
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
I suppose you are refreshing page using F5 or by right clicking on page and opting refresh option or using refresh button of browser. If this is the case then I am scared it's not refresh, it's repeating previous action. That means if you were searching for flight and refreshing using above options, it will again search for flight using same search criteria. You can confirm it by putting debugger on search event. You can avoid this behavior by setting and clearing Session or ViewState and manage label text using it.

How to make a button refill a GridView each time it's clicked

I have a dropdown menu in Visual Studio and when a selection is made, a user clicks a button. Then the button fills a GridView.
It works for one time, but if I select something a second time and click the button, nothing happens. How do I make it refresh or do the action again?
Button Click in C#:
protected void ButtonChangeEvent_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["Events2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("spRegistrantsGridView"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "SELECT");
cmd.Parameters.Add("#EventId", SqlDbType.Int).Value = DropDownListEvent.SelectedValue;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
Check the value of DropDownListEvent.SelectedValue when you click button for 2nd time. I suspect it takes the 1st value from ddl always. This happens if you have bound ddl in Page_Load event handler without putting !IsPostBack condition check.
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) {
// bind dropdownlist here
}
}

Asp.net dropdownlist getselectedvalue doesnt return anything

Im having a problem with a dropdownlist in asp.net.
When i try to get the selected value of the list it doesnt return anything.
The aspx looks like this
<div class="form-signin">
<h2 class="form-signin-heading">Slet besked</h2>
<div class="input-group">
<span class="input-group-addon">ID</span>
<asp:dropDownList runat="server" CssClass="form-control" ID="sletBox" />
</div>
<asp:Button runat="server" CssClass="btn btn-lg btn-block btn-danger" Text="Slet" OnClick="Slet" />
</div>
And the kode behind it looks like this
protected void Slet(object sender, EventArgs e)
{
Response.Write("wow der sker noget");
Response.Write(sletBox.SelectedItem.Value);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection myconnection = new SqlConnection();
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder();
myconnection.ConnectionString = constr;
myconnection.Open();
string sqlcmd = "DELETE FROM messages WHERE messageid = '" + sletBox.SelectedValue.ToString() + "'";
SqlCommand messageDelete = new SqlCommand(sqlcmd, myconnection);
messageDelete.ExecuteNonQuery();
myconnection.Close();
}
The only thing that works is the response.write(wow) not the selectedvalue
EDIT:
The page_load code
protected void Page_Load(object sender, EventArgs e)
{
DataTable subjects = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}
You're doing the databinding for the dropdownlist in the pageload and not checking for IsPostBack. As a result when the button triggers the clik it resets the selectedvalue. Change you PageLoad like below
if (!IsPostBack)
{
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}
As a side note as Mathew suggested try adding using to better manage your connections objects so it's properly disposed after it's been used.
You must load your DropDownList data only if IsPostBack is false, otherwise you'll be reloading the control every postback. Once the data bound to the control is changed, the selected value is lost as well. Keep in mind that the Page_Load event is fired when the SelectedIndexChanged event occurs.
if(!Page.IsPostBack)
{
DataTable subjects = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}

Deleting checked records from table in asp.net [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am not able to recognize what I am doing wrong in my code. Can someone help ? I want to delete all the images which are checked using c# .
my code snippet looks like this :-
SqlConnection con = new
SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
SqlDataAdapter adap;
DataSet ds;
string Query;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
protected void binddata()
{
string str = "select * from photos";
SqlCommand cmd = new SqlCommand(str, con);
adap = new SqlDataAdapter(str, con);
ds = new DataSet();
adap.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
con.Open();
String mySQL;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)
Repeater1.Items[i].FindControl("CheckBox1");
if (((CheckBox)Repeater1.Items[i].FindControl("CheckBox1")).Checked)
{
//This assumes data type of messageID is integer, change (int) to the right type
CheckBox CheckBox = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1");
Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("literal1");
string Id = litMessageId.Text;
mySQL = string.Format("delete from photos where id = '{0}'", Id);
SqlCommand cmdDelete = new SqlCommand(mySQL, con);
cmdDelete.ExecuteNonQuery();
// Continue your code here
}
else
{
}
}
}
catch
{
Label2.Text = "errror";
}
}
.aspx page contains :-
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<img src='images/<%#DataBinder.Eval(Container.DataItem,"images") %>' height="150" width="150" alt="" border="0" />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</br>
</ItemTemplate>
</asp:Repeater>
Thanks in advance :)
Here are some pointers:
The names you use are difficult to understand in your codebehind. You now have 1 repeater but in case you have multiple it is better to use a more specific name.
Depending on the .NET version you can use generic types to declare your variables.
SqlCommand cmd = new SqlCommand(str, con);
becomes:
var sqlCommand = new SqlCommand(queryString, connectionString);
Your not closing the connection. If your in newer versions of .NET the best approach would in my opinion be:
private string ConnectionString = webConfigurationManager.ConnectionStrings["connectionstring"] != null ? WebConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString : "";
if (!string.IsNullOrEmpty(this.ConnectionString))
{
using (var sqlConnection = new SqlConnection(this.ConnectionString))
{
//your code here
}
}
You are catching an error but your not doing anything with the provided information.
use:
Catch (Exception exception)
{
ErrorLabel.Text = string.format("The following error has occurred: {0}.", exception.Message);
}
to use the exception.Message where desired.
In modern implementations you are most probably better off using an MVC application using EntityFramework and MVC Razor.
Defining your SQL queries like that is dangerous also. If I edit the post value of the literal to something like "ID AND 1 = 1" I will now delete all photos.
Here are some pages to help you get started with Entityframework and MVC:
http://www.asp.net/mvc/tutorials
http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B
I will give you some good pointers in improvements in a minute. First try this and change the literal value to the column you use as an id in case I got it wrong:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<img src='images/<%#DataBinder.Eval(Container.DataItem,"images") %>' height="150" width="150" alt="" border="0" />
<asp:Literal ID="Literal1" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"id") %>'></asp:Literal>
</br>
</ItemTemplate>
</asp:Repeater>
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
SqlDataAdapter adap;
DataSet ds;
string Query;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
protected void binddata()
{
string str = "select * from photos";
SqlCommand cmd = new SqlCommand(str, con);
adap = new SqlDataAdapter(str, con);
ds = new DataSet();
adap.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
con.Open();
String mySQL;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1")
Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("literal1");
if (CheckBox1 != null && litMessageId != null && CheckBox1.Checked)
{
string Id = litMessageId.Text;
mySQL = string.Format("delete from photos where id = '{0}'", Id);
SqlCommand cmdDelete = new SqlCommand(mySQL, con);
cmdDelete.ExecuteNonQuery();
// Continue your code here
}
else
{
}
}
}
catch
{
Label2.Text = "error";
}
}

Categories