i have tried to to load the data to text box, while selecting the drop down list, i was created a class for retrieval and called it in drop down list selected index changed. But i cant get the answer what i want. If i have called the class in Button click event it has worked properly. So please correct me. What i made a mistake. This is what my code:
public void so()
{
con.Open();
string s2;
s2 = "select Source from tbl_component where Componetcode='" + Mcodeddl.SelectedItem.Text + "'";
SqlCommand c2 = new SqlCommand(s2, con);
SqlDataReader d2;
d2 = c2.ExecuteReader();
while (d2.Read())
{
TextBox1.Text = d2["Source"].ToString().Trim();
}
d2.Close();
con.Close();
}
//i have called the so class here
protected void Mcodeddl_SelectedIndexChanged(object sender, EventArgs e)
{
so();
}
You should set a breakpoint inside your Mcodeddl_SelectedIndexChanged method to see if the event is triggered, also make sure include AutoPostBack="true" in your dropdownlist definition
Make sure you have specified OnSelectedIndexChanged event for the drop down in aspx page
<asp:DropDownList ID="Mcodeddl" runat="server"
OnSelectedIndexChanged= "Mcodeddl_SelectedIndexChanged">
</asp:DropDownList>
Also use parameterized SQL queries.
PS. Your SO(); is a method not a class.
i have got the answer. And i gave the detail what exactly i have did.
"Set AutoPostBack=True"
Related
When I choose any option from the dropdown list and then insert it into the database, the first option is chosen automatically, even if I choose the second or third option; only the first option is inserted each time.
Order.aspx.cs
protected void selectList()
{
conn = new SqlConnection(connstr);
conn.Open();
sql = "SELECT * FROM Product";
SqlCommand comm = new SqlCommand(sql, conn);
adap = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
adap.Fill(ds);
ProductID.DataTextField = ds.Tables[0].Columns["Name"].ToString();
ProductID.DataValueField = ds.Tables[0].Columns["Id"].ToString();
ProductID.DataSource = ds.Tables[0];
ProductID.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
bindGrid();
selectList();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
selectList();
sql = "INSERT INTO [Order] (CustomerID,ProductID ,EmployeeID,Quantity,Date) VALUES ('" + CustomerID.Text + "','" + ProductID.SelectedValue + "','" + EmployeeID.Text + "','" + Quantity.Text + "','" + Date.Text + "')";
conn = new SqlConnection(connstr);
conn.Open();
comm = new SqlCommand(sql, conn);
comm.ExecuteNonQuery();
conn.Close();
bindGrid();
ScriptManager.RegisterStartupScript(Page, Page.GetType(),
"myPrompt", "alert('Successfully Updated!');", true);
}
Order.aspx
Product ID:
<asp:DropDownList ID="ProductID" runat="server" CssClass="form-control" ></asp:DropDownList>
Actually, the mistake here is the page load. In 99% of ALL pages, you only want to bind and load up on the first page load. And most if not all asp controls will automatic persist for you. So, your big mistake is this:
protected void Page_Load(object sender, EventArgs e)
{
bindGrid();
selectList();
}
The above has to become this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGrid();
selectList();
}
}
In fact, you really can't build a functional web form page unless you follow the above rule. Remember, any button, any post-back, and the page load event will run again.
So yes, page load is the right place, but you in near 99% of cases need to wrap that code in the all important isPostBack = false code stub.
Once you do above, then your whole page will operate quite nice, quite normal, and in near all cases, you find the controls correct persist their values and settings.
So, no, page load is NOT too soon, and page load is VERY much the correct event and place to load up the data bound controls - but, you only want to do this on the really first page load.
In fact, there is probably 1 question near per day on SO, and their woes and problems can be fixed by following the above simple rule. Failure to note the above isPostBack? You can't really even build a working asp.net page.
Page_Load() is too late to bind your list.
Remember, when using web forms, you start from scratch and have to recreate all of your data items on every single request... even simple button click events*. This is why you call bindGrid() in the Page_Load() method. However, part of this process also involves restoring ViewState, so the button click will know what item was selected. The problem is this ViewState data is restored before the Page_Load() method is called. Therefore the grid is still empty, and the SelectedValue information you need to get from ViewState cannot be set correctly.
You can fix this by moving the code that binds your grid data up to the Init or Pre_Init events.
While I'm here, I need to reiterate my comment about SQL Injection. This is a really big deal... the kind of thing that's too important to do wrong even with learning and proof-of-concept projects. I suggest using Google to learn more about using parameterized queries with C#.
Additionally, it's rare to insert selections directly into an Orders table. Often there's a separate "ShoppingCart" table, using a Session Key for the table's primary key, where the user can build up the cart before completing the order and creating the final Order and OrderLines or OrderDetail records.
* For this reason, it's often worthwhile in web forms to do more of this work on the client browser, in javascript.
I have drop-down inside of a gridview so when the gridview is loaded and the drop-down is bound then the drop-down only show the first value of the drop-down list and it is not showing the previously selected value. When the gridview loads, i would like the drop-down to show what was previously selected for that row. Here is my code:
aspx markup for the drop-down:
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_Answer" runat="server">
</asp:DropDownList>
</ItemTemplate>
Here is code behind:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl_Answer;
//get current index selected
int current_quest = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList;
using (SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString))
{
con2.Open();
using (SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from table1 where ID= '" + current_quest + "' ", con2))
{
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
}
con2.Close();
}
}
I have tried to add this line of code after binding but i get this error "Object reference not set to an instance of an object"
ddl_Answer.Items.FindByValue((e.Row.FindControl("lblAns") as Label).Text).Selected = true;
thanks
I believe in your SELECT you need to use current_quest_sk instead of current_quest
Aslo try to check for null before accessing your controls:
var ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList;
var answerLabel = e.Row.FindControl("lblAns") as Label;
if(answerLabel !=null && ddl_Answer!=null)
{
ddl_Answer.Items.FindByValue(answerLabel.Text).Selected = true;
}
#afzalulh has a valid point remove quotes if current_quest_sk(ID) is an Integer in your table.
You should avoid SQL injection but that's a different topic.
Place a breakpoint in your code, and setup through it with your debugger.
Either you have a typo in one of your string names or you are looking at the wrong control.
Stepping through your code will help you see exactly what line of your code is causing the problem.
You could also put a try/catch block around the whole thing to help you isolate the problem. Once you find the problem, remove the try/catch block.
I have set selected item of the DropDownList in PageLoad.
protected void Page_Load(object sender, EventArgs e)
{
strSelect2 = "SELECT * FROM [Order] WHERE orderId = '" + selOrder + "'";
cmdSelect3 = new SqlCommand(strSelect2, conNWind);
conNWind.Open();
dtrReader = cmdSelect3.ExecuteReader();
if (dtrReader.Read())
{
DropDownList1.Text = dtrReader["status"].ToString();
}
conNWind.Close();
After that, I have another function to retrieve the ID of the selected item in the DropDownList.
String cmd1 = "Select * from [Status] WHERE statusName = #statusName";
SqlCommand cmdSelectCat = new SqlCommand(cmd1, a);
a.Open();
cmdSelectCat.Parameters.AddWithValue("#statusName", DropDownList1.SelectedValue);
dtrReader = cmdSelectCat.ExecuteReader();
if (dtrReader.Read())
{
statusId = dtrReader["statusId"].ToString();
}
a.Close();
When I choose another item in the DropDownList, I try to print on a label using a function on a button.
Label9.Text = DropDownList1.SelectedIndex.toString();
But the statusId I get is the ID where the DropDownList select upon PageLoad. How can I get the value of the selected item but not the selected item in the page load? Beside's using IsPostBack
The short answer is that you're trying to combine server-side and client-side code. You've got a global setup and load via ASP.Net, then the 'on-change' of the Selection List is doing some kind of postback to call a server-side function.
You're setting it up to do a request to the server, so it reloads the entire page. And resets the selection in the box, too, probably. Or doesn't do anything. Regardless, you have weird functionality because you're trying to mix functionality between client and server.
I suggest you debug through putting a stop point at the start of your Page_Load() and the start point of your function and seeing what exactly the server is doing after you change the value. Most likely you will be surprised at the order of operations.
To do what I think you're trying to do, I think you'll probably have to use either IsPostBack or Javascript. Sorry.
I suggest you look at this post:
ASP.NET DropDownList OnSelectedIndexChanged event not fired
I think that there might be some help for you inside.
I have the following markup:
<td>
<asp:DropDownList runat="server" ID="ddlExtRouteBusyID" style="width: 320px;" />
</td>
And code behind that executes on page load:
//Bind the route busy drop down list:
DataTable dr = /*[some DataTable returned from a wrapper to an RDBMS*/;
this.ddlExtRouteBusyID.DataSource = dt;
this.ddlExtRouteBusyID.DataTextField = "description";
this.ddlExtRouteBusyID.DataValueField = "id";
this.ddlExtRouteBusyID.DataBind();
I cannot seem to access the description and ID data based upon the value of the SelectedItem/Value. For example if I select the second list item, the SelectedIndex is 1, but the description might be "server2" and the ID might be 1118. How can I pull the description and ID values?
Thanks.
You can use the following to get the text and the value:
ddlExtRouteBusyID.SelectedItem.Text
ddlExtReouteBusyID.SelectedItem.Value
If this doesn't work there may be some other problem with what the page is doing, since I just verified that these worked for me.
There are some things not cleared in question, so here are some of the Options I thought about..
1) If you want to access value and text client side you can use simple JQUERY as follows..
$("#ddlExtRouteBusyID.ClientID").change(function() {
selectval();
});
$("#ddlExtRouteBusyID.ClientID").click(function() {
selectval();
});
function selectval(){
alert('Text:' + $('#ddlExtRouteBusyID.ClientID :selected').text() + ', value = ' + $("#ddlExtRouteBusyID.ClientID").val());
}
2) Use the values on server side then HOW?, I mean onSelectedIndexChange or On Any ButtonClick event
Note : to use any way the dropdownlist databind method should be kept in if(!IsPostBack)
You need to add two properties to your DropDownList definition, OnSelectedIndexChanged and AutoPostBack, like this:
<asp:DropDownList runat="server" ID="ddlExtRouteBusyID" style="width: 320px;"
OnSelectedIndexChanged="Index_Changed" AutoPostBack="true" />
Now you need to write code in your code-behind to handle the SelectedIndexChanged event, like this:
protected void Index_Changed(Object sender, EventArgs e)
{
// Put logic here to grab values from drop down list
Label1.Text = "You selected " + ddlExtRouteBusyID.SelectedItem.Text +
" with a value of " + ddlExtRouteBusyID.SelectedItem.Value +
".";
}
Note: AutoPostBack=true is what causes the page to post back to the server when the drop down list value changes; otherwise the drop down list change event will not fire.
So I've got a class, commenter, and two methods within that class, SaveBtn_Click - created primarily not by me, and then also PeerReview, primarily created by me.
Anyway, the code starts off like this (after a variety of using statements):
public partial class commenter : System.Web.UI.Page
{
string employee_reviewed;
PeerReview pr = new PeerReview();
public void SaveBtn_Click(object sender, EventArgs e)
{
//all the information for the SaveBtn_Click method.
}
After that, I have PeerReview:
public void PeerReview(System.Web.UI.WebControls.ListBox listbox)
{
MySqlConnection con = new MySqlConnection("server=localhost;database=hourtracking;uid=username;password=password");
MySqlCommand cmd = new MySqlCommand("select first_name from employee where active_status=1", con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
Console.WriteLine("Another test!");
Console.WriteLine(r);
Console.WriteLine("Hi, this is a test!");
while (r.Read())
{
listbox.Items.Add(new ListItem(Convert.ToString(r["first_name"]), Convert.ToString(r["first_name"])));
}
con.Close();
}
I'm connecting this with ASP.NET, and I can get the listbox to show up, but not the individual items in the listbox. I'm testing it with a console.writeline command, to see if that outputs anything - but nothing is being put out on the ASP page.
I'm not certain how I should reference these particular sections (new to C#, asking like 3 dozen questions about this).
ASP code looks like this:
<asp:ListBox ID="listBox1" runat="server">
You have some confused declarations.
You declare a method called PeerReview, but you also have an attempt to create an instance of PeerReview as though it were a type. I think you really just want to call the PeerReview method from your button click event, eg
public void SaveBtn_Click(object sender, EventArgs e)
{
PeerReview();
}
And then eliminate the "PeerReview pr = new PeerReview();" line. Also, as this is on a page, you have an implicit reference within the partial class to the listbox by its ID, so you don't need to pass it as a parameter. And the Console.WriteLines are not useful in a web application - you might try Response.Write if you're wanting to add that to the output for debug purposes.
Edits based on OP response
You should call PeerReview in the Page_Load event handler:
public void Page_Load(object sender, EventArgs e)
{
// You need to determine if you should call PeerReview every time the page
// loads, or only on the initial call of the page, thus determining whether
// you need the IsPostBack() test. My instinct is that you *do* want to constrain
// it to the first pass, but only you can make that determination for
// certain based on your requirements.
if (!Page.IsPostBack) //Do you need this check?
{
PeerReview();
}
}
You're trying to add items to listbox though your listBox has an id of listBox1
Rather than looping through your data and adding items why not bind the datasource to your listbox and then set the DataTextField and DataValueField on your listbox.
So for example (typos may exist..sorry.. been a while since i wrote C#)
MySqlConnection con = new MySqlConnection("server=localhost;database=hourtracking;uid=username;password=password");
MySqlCommand cmd = new MySqlCommand("select first_name from employee where active_status=1", con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
listBox1.DataSource = r;
listBox1.DataBind();
con.Close();
If you can't bind to the reader (can't remember..) then dump your results into a datatable first, then bind to the listBox1
DataTable dTable = New DataTable();
dTable.Load(reader);
listBox1.DataSource = dTable;
listBox1.DataBind();
in your asp, set the listBox fields like:
<asp:ListBox ID="listBox1" runat="server" DataTextField="first_name" DataValueField="first_name">
quick view here is you are adding items to listbox instead of listBox1
change:
listbox.Items.Add(new ListItem(Convert.ToString(r["first_name"]), Convert.ToString(r["first_name"])));
to:
listBox1.Items.Add(new ListItem(Convert.ToString(r["first_name"]), Convert.ToString(r["first_name"])));