OK, I've completely given up. I'm trying to write what should be a simple query from in an asp.net C# web page using Visual Studio 2017. For the life of me, I can't figure out what's going wrong, and I can't find an answer (that I understand) anywhere. So I need help.
I have an asp button (ID=submit) on my form and one text box (ID=textbox1). The connectionstring per my SQL data source is
Provider = Microsoft.Jet.OLEDB.4.0; Data Source =| DataDirectory |\TheList.mdb
How the hell can I get the submit button to run an SQL query that searches the value of textbox1 against my database field "Name" and display the results in a FormView.
I want/need to learn this, so I appreciate any helpful links, but damned if I haven't been googling this every which-way for 2 solid weeks now, so I'd also be happy with some basic code.
Thanks!
Just create a simple onclick() event inside it use stored Procedure Or a Query which will return a value. Then assign that value to the Textbox
In .aspx
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit"/>
now in .aspx.cs
protected void Submit(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("GetFruitName", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FruitId", int.Parse(txtFruitId.Text.Trim()));
cmd.Parameters.Add("#FruitName", SqlDbType.VarChar, 30);
cmd.Parameters["#FruitName"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lblFruitName.Text = "Fruit Name: " + cmd.Parameters["#FruitName"].Value.ToString();
}
}
}
refer this Link for further refference
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 a webpage called blogwebsite and in that I have a textbox and search button. I am passing the value of textbox on button click to another webform called blogseacrh through session. I also have a database bound through these webforms. In this blogsearch webpage I have taken the session variable in a textbox. Using this textbox value I am writing a oledbcommand select query. I am fetching data from the database using this textbox value and want to display it on the blogsearch webpage. For this to happen I am using oledbdatareader to read the data and then write the fetched data in the textbox. But when I am running the webpage when I click on search button it gives me the error at the oledbdatareader line saying that no given value given for one or more required parameters.
I really can't understand what I am doing wrong. Can someone please give me a solution?
This is the button click event which is working perfectly
protected void btn_srch_Click(object sender, EventArgs e)
{
Session["name"] = txt_bnm.Text;
Response.Redirect("blogseacrh.aspx");
}
This is the code that needs to be executed on another webpage on button click event
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null)
{
con.Open();
txt2_bnm.Text = Session["name"].ToString();
cmd = new OleDbCommand("select user from tbl_blogs where book_name='" + txt2_bnm.text + "',con); `
OleDbDataReader d = cmd.ExecuteReader();
while (d.Read())
{
user = d["user"].ToString();
Response.Write(user);
}
cmd = new OleDbCommand("select blogs from tbl_blogs where book_name='" + txt2_bnm.Text + "' ", con);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
blogs = dr["blogs"].ToString();
Response.Redirect(blogs);
}
con.Close();
}
I have also checked all the field names and table name and they are all correct as well.
Can someone please solve this error. i have an assignment to complete please.
I'm using the DEVExpress's gridview and have this code that deletes the selected gridview row from another control's customcallback,
the line
GridFrom.DeleteRow(int.Parse(rowKey[2]));
retrieves the correct visibleIndex but does not remove the row from the gridview. The databind also does not refreshes the gridview's data and it requires refreshing of the page for the data to update
protected void ASPxTreeList1_CustomCallback(object sender, DevExpress.Web.ASPxTreeList.TreeListCustomCallbackEventArgs e)
{
string[] rowKey = e.Argument.Split('|');
string strConnectionString = ConfigurationManager.ConnectionStrings["dbname"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strConnectionString))
{
string query = "DELETE FROM Table WHERE id=#id";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#id", rowKey[0]);
cmd.ExecuteNonQuery();
conn.Close();
}
}
GridFrom.DeleteRow(int.Parse(rowKey[2])); //rowKey[2] is the visibleIndex
GridFrom.DataBind();
}
}
it requires refreshing of the page for the data to update
You don't see grid changes, because ONLY ASPxTreeList is updated during ITS OWN callback.
As a possible solution, disable ASPxTreeList's callbacks or delete a grid row using the grid's CustomCallback instead (in a similar manner).
<dx:ASPxTreeList ID="ASPxTreeList1" runat="server" EnableCallbacks="false">
</dx:ASPxTreeList>
Check the The concept of callbacks - Why is it impossible to update external control data during a callback to another control learning guide regarding this.
Background information:
I have a SQL connected datalist, one of the columns is called work_order
In the datalist I have inserted a button btn_Start. The button is populated at the end of each set
The goal of the btn_Start is to do a database insert, the insert needs to includes the work_order value from the set of data the button is clicked in (so the insert can be tied to the work_order value.)
btn_Start code:
protected void btn_Start(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["nothanks"].ConnectionString))
{
String query = "INSERT INTO [TimeTest] ([Starttime], [Work_Order]) VALUES (#Starttime, #Work_Order)";
using (SqlCommand CCC = new SqlCommand(query, connection))
{
connection.Open();
CCC.CommandType = CommandType.Text;
CCC.Parameters.Add("#Starttime", SqlDbType.DateTime).Value = DateTime.Now;
CCC.Parameters.Add("#Work_Order", SqlDbType.Int).Value = lb_User1.Text.ToString();
CCC.ExecuteNonQuery();
}
}
}
To grab text of the work_order column, I'm using the itemcommand event to propagate a label (lb_User1).
DataList1_ItemCommand` code:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
DataList2.SelectedIndex = e.Item.ItemIndex;
lb_User1.Text = (DataList2.SelectedItem.FindControl("Work_OrderLabel4") as Label).Text;
}
This works well, each time btn_Start is pushed, lb_User1 is updated with the right information.
The issue: when btn_Start is clicked, both btn_Start and DataList1_ItemCommand fire. But DataList1_ItemCommand fires after btn_Start. Which means lb_User1 isn't updated with the right info yet, and as such the insert fails to work as needed.
NOTES:
the lb_User1 isn't needed, I planned to go direct to the SQL insert. lb_User1 was used for code testing (so I can see what's going on)
My objective is to do the SQL insert with the grabbed data from datalist (Work_OrderLabel4). If I can accomplish this objective a better way that would also solve the issue.
btn_Start isn't going to be the only button in the datalist. One possible solution is go way from having two events and only doing things under the itemcommand event, but how do you separate out which button fires, without involving their respective events.
Objective: I'm trying to get each embedded start button to grab its corresponding work_order value for use in a SQL insert. The above is trying to accomplish this task, I'm almost there but I'm having the issue stated above. I'm open for other ways to accomplish this task (see picture of clarification)
Additional Information:
protected void DL_Main_ItemCommand(object source, DataListCommandEventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
{
String query = "INSERT INTO [TimeTest] ([Starttime], [Work_Order]) VALUES (#Starttime, #Work_Order)";
using (SqlCommand CCC = new SqlCommand(query, connection))
{
connection.Open();
CCC.CommandType = CommandType.Text;
CCC.Parameters.Add("#Starttime", SqlDbType.DateTime).Value = DateTime.Now;
// All you need is the value of Work_OrderLabel4 of the selected item so just do it like this.
CCC.Parameters.Add("#Work_Order", SqlDbType.Int).Value = (DL_Main.SelectedItem.FindControl("Work_OrderLabel") as Label).Text;
CCC.ExecuteNonQuery();
}
}
}
After Running
Get rid of btnStart and put the code below in your DataList1_ItemCommand. The only line I changed is the one with my comment:
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["nothanks"].ConnectionString))
{
String query = "INSERT INTO [TimeTest] ([Starttime], [Work_Order]) VALUES (#Starttime, #Work_Order)";
using (SqlCommand CCC = new SqlCommand(query, connection))
{
connection.Open();
CCC.CommandType = CommandType.Text;
CCC.Parameters.Add("#Starttime", SqlDbType.DateTime).Value = DateTime.Now;
// All you need is the value of Work_OrderLabel4 of the selected item so just do it like this.
CCC.Parameters.Add("#Work_Order", SqlDbType.Int).Value = (DataList2.SelectedItem.FindControl("Work_OrderLabel4") as Label).Text;
}
CCC.ExecuteNonQuery();
}
}
Also, as a side note, please give your controls better names than DataList1. Perhaps DataListTimeTest since it deals with TimeTest table.
I was wondering how could I retrieve the data from SQL server compact database that I just saved and insert it into textbox of newly created form. The source code is not complete, I just wanted to save space. Connection is fine, and I'm able to add data into database in the actual program. I just would like to know how to retrieve it and put it into textbox of newly created form. This is done in WinForms.Thank you!
public void b1_Click(object sender, EventArgs e)
{
SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name) VALUES (#Name, #LastName)", conn);
command.Parameters.AddWithValue("#Name", t1.Text);
command.ExecuteNonQuery();
}
private void b2_Click(object sender, EventArgs e)
{
Form form2 = new Form();
form2.Show();
t3.Location = new System.Drawing.Point(0, 35);
t3.Size = new System.Drawing.Size(85, 15);
//access database and insert data into textbox
t3.Text = ?
form2.Controls.Add(t3);
}
Well it's not to hard to just get a value from the database, something like this should suit your needs:
SqlCeCommand command = new SqlCeCommand("SELECT * FROM tbl1(Name) WHERE name = #Name AND last_name = #LastName", conn);
command.Parameters.AddWithValue("#Name", "Hank");
command.Parameters.AddWithValue("#Name", "Hill");
SqlDataReader reader = command.ExecuteReader();
t1.Text = reader.GetString(0);
t2.Text = reader.GetString(1);
When in doubt, start at the official docs. See this sample, on msdn: http://msdn.microsoft.com/en-us/library/aa226134(v=sql.80).aspx
They show there a couple of SQL commands like SELECT, INSERT and UPDATE. You know how to insert, so you are now interested in the SELECT part. See how they use data reader and try that for starters.
Here is an example:
http://msdn.microsoft.com/en-us/library/aa983340(v=VS.80).aspx
Please also check codeplex.com for additional examples/projects