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.
Related
I have two dropdownlists, ddlstates and ddlcitys.
The ddlstates has a list of Brazilian states that when clicked, loads the ddlcitys with the cities of that state. Until then, everything works correctly, but when clicking the save button which makes verification of completed fields or not, the ddlcitys back to the first option. How to store the information ddlcitys before the postback?
In code behind, have code that loads the ddlcitys:
protected void ddlstates_TextChanged(object sender, EventArgs e)
{
if (ddlstates.Text != "")
{
List<ListItem> cidades = new List<ListItem>();
SqlConnection conn = new SqlConnection(mytools.stringconection);
SqlDataReader dr = null;
conn.Open();
SqlCommand cmd = new SqlCommand("select ciddesc from cidades where cidestsigla = '" + ddlstates.SelectedValue.ToString() + "' order by 1 asc");
cmd.Connection = conn;
dr = cmd.ExecuteReader();
ddlcitys.Items.Clear();
while (dr.Read())
{
cidades.Add(new ListItem(dr[0].ToString()));
}
dr.Close();
conn.Close();
ddlcitys.DataTextField = "Text";
ddlcitys.DataValueField = "Value";
ddlcitys.DataSource = cidades;
ddlcitys.DataBind();
}
}
Asked long time ago, anyway may the answer help anyone.
On your page load event before bind any of your dropdownlists, make sure that not post back, then on your dropdown select change events , your dropdown values will not re bind so values will not changed.
hint : make sure that your aspx page enable view state (by default enabled) read more.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
//this will called when your page loaded at first time, so bind your drop down values here.
} else {
//this will called on select change, don't bind your dropdown again, then values will be same (asp.net web forms viewstates will handle read more about viewstate).
}
}
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.
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"])));
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Data not writing out to Database
I'm trying to update a bit field in my database on a checkbox's checkedchanged event. When it gets checked, it sends a 1. When it is unchecked, it sends a 0. Now I'm not sure why, but these changes only get saved SOME of the time. Would this have anything to do with the "!IsPostBack" ?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
{
connection.Open();
dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);
dataSet = new DataSet();
dataAdapter.Fill(dataSet, "SecureOrders");
DataView source = new DataView(dataSet.Tables[0]);
DefaultGrid.DataSource = source;
DefaultGrid.DataBind();
connection.Close();
}
}
}
protected void CheckBoxProcess_CheckedChanged(object sender, EventArgs e)
{
bool update;
string checkedString = "UPDATE SecureOrders SET processed = 1 WHERE fName LIKE '%" + DefaultGrid.SelectedRow.Cells[2].Text + "%' AND lName LIKE '% " + DefaultGrid.SelectedRow.Cells[3].Text + "%'";
string uncheckedString = "UPDATE SecureOrders SET processed = 0 WHERE fName LIKE '%" + DefaultGrid.SelectedRow.Cells[2].Text + "%' AND lName LIKE '% " + DefaultGrid.SelectedRow.Cells[3].Text + "%'";
CheckBox cb = (CheckBox)sender;
GridViewRow gvr = (GridViewRow)cb.Parent.Parent;
DefaultGrid.SelectedIndex = gvr.RowIndex;
update = Convert.ToBoolean(DefaultGrid.SelectedValue);
orderByString = orderByList.SelectedItem.Value;
fieldString = searchTextBox.Text;
connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
{
connection.Open();
SqlCommand checkedCmd = new SqlCommand(checkedString, connection);
SqlCommand uncheckedCmd = new SqlCommand(uncheckedString, connection);
if (cb.Checked == true)
{
checkedCmd.ExecuteNonQuery();
}
else
{
uncheckedCmd.ExecuteNonQuery();
}
connection.Close();
}
I would recommend setting "EnableViewState" to false on your DataView, and then moving the code from the if (!IsPostBack) section to your page's Pre_Init event. I think that will solve your problem and possibly also help your postbacks go faster.
The !IsPostBack is not your issue, whether or not I like the pattern. The postback event handler is a mess, however.
You have left open a potential SQL injection hole by concatenating strings rather than using parameters. Even if you have to write a sproc and pass in a comma separted list, you are better off than the code you have.
Your decision point is one whether or not a value is set to 1 or 0, yet you branch code on the point of deciding which of two strings to run (one will always be created, consuming cycles, yet NEVER run).
You are creating two command objects, one of which will NEVER be used.
You can determine where things are going wrong by stepping through the code with a wide variety of test cases. Eventually you will hit the one that triggers the issue you have.
A better option would be to separate out the SQL update code into its own routine and send the parameters in. This will reduce the number of moving parts. The only thing that should be in the main event handler (and this can be argued) is the grabbing of the variables from the Grid.
If it were me, I would also consider using the key value for my update statement, lest you have two James Smith's in the database, both which are now processed.
As for candidates why it updates some times and not others? Could very well be that you are ending up with the wrong selected row for some reason. As I don't have a copy of your code to see all the permeatations, I can only guess.
I've got a gridview displaying product instance info; I need a hyperlink in my Action column to bring up an view/edit page that displays the row data. How do I make the link bring up the data from that specific row into the edit page?
Note: there are other questions with similar titles, however, they do not cover this specific topic.
Use datakeys in the gridview, using datakey will get you the id of each clicked hyperlink , and then you can use that id to edit or delete the selected items easily. In the code behind just find the hyperlink control , pass the data key and write d update sql for it. Inorder to move your data to other pages you can sessions but if you are developing a commercial website session wont be a good idea due to its security issues, use cookies in that case .
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["productID"] != null)
{
productID = Convert.ToInt32(Request.QueryString["productID"]);
bindData(productID)
}
...
}
}
protected void bindData(int productID)
{
//to avoid sql injection as mentioned below use parameters
SqlConnection conn = new SqlConnection(ConnectionString); // define connection string globally or in your business logic
conn.Open();
SqlCommand sql = new SqlCommand("Select * From [Table] Where ID = #productID",conn);
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#ID";
parameter.Value = productID;
sql.Parameters.Add(parameter);
conn.close()
}
You can also use Microsoft.ApplicationBlocks.Data.dll to avoid repeating ado.net , it will reduce your code.
Try something like this?
ViewProducts.aspx:
<columns>
<asp:HyperLinkField DataNavigateUrlFields="ProductID" HeaderText="Edit"
ItemStyle-Width="80"
DataNavigateUrlFormatString="EditProduct.aspx?productID={0}"
Text="Select" ItemStyle-HorizontalAlign="Center" />
...
</columns>
EditProduct.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["productID"] != null)
{
productID = Convert.ToInt32(Request.QueryString["productID"]);
...
}
...
}
}
There are n+1 ways to solve this problem. If you are using the sql data source you can accentually have VS generate the sql and edit logic for you if you don't have specific requirements. here is a code project tutorial.
Another oft used tactic is to add a command button to the row and populate the command argument with the ID of the row you want to edit then in the oncommand event handle what ever logic you need.
you can also use a simple html link and and use get parameters. Or you can session like I said there a a ton of ways to solve this problem.