button and itemcommand event sequence - c#

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.

Related

ASPxGridView DeleteRow not deleting on another control callback

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.

Simple Database Query Button

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

c# how to access data fields of the selected in DataGridView database record

I'm new to the database programming, so I have probably very simple question.
On the form I have a DataGridView which shows all records from the SQL database, from single table. When I select a line (OnRowEnter event), I would like to display the same data in the textBoxes, which are not binded to the DataSource, but I do not know how to access the selected record and its fields.
I have seen many examples which use SQL statements, but is it the only way? Or is there a simpler method. I thought I should be able to access the current record and its fields almost directly? Is it possible?
I'm using Visual Studio Community 2013
Thx in advance for your help.
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
string asd = dataGridView1.Rows[e.RowIndex].Cells["NameOfColumn"].Value.ToString();
}
You can access any column of any row by this line.
EDIT:
You just told me you want to populate 2 textboxes from database and on buttons(save - overwrite) you want to save/overwrite it. So why you do not populate it from database
using (FbConnection con = new FbConnection(connectionString))
{
con.Open();
using (FbCommand cmd = new FbCommand("SELECT TEXT1, TEXT2 FROM TABLE WHERE CONDITION", con))
{
FbDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
}
con.close();
}
and then after user press save you just take whole text and update database
using (FbConnection con = new FbConnection(connectionString))
{
con.Open();
using (FbCommand cmd = new FbCoimmand("UPDATE TABLE SET TEXT1 = #Text1, TEXT2 = #Text2 WHERE CONDITION))
{
cmd.Parameters.AddWithValue("#Text1", textBox1.Text);
cmd.Parameters.AddWithValue("#Text2", textBox2.Text);
cmd.ExecuteNonQuery();
}
con.Close();
}
if user is writing text in some other textbox and you want to add that text to current text in database so you just read text from database and put it in string, on that string you add string from user and save like that to database

How do I insert data to a database without clicking the insert button

I am using ASP.NET 4.5 C#
I have a FormView in Insert mode, linked to an MSSQL database, with 2 hidden fields in it.
These fields are populated when the page loads.
I now need this data to be inputted to the database automatically without anyone having to click on an insert button.
How do I achieve this once the data has bound?
Here is the code I have been trying, it's working except the adnumber value is not uploading, only the date
protected void FormView1_DataBound(object sender, EventArgs e)
{
string ad, insertqry;
ad = ((HiddenField)(FormView1.FindControl("Adnumber"))).Value;
DateTime hit = DateTime.Now;
insertqry = "insert AdvertsHits(ad,hit) values(#ad,#hit)";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand(insertqry, con);
cmd.Parameters.Add("#ad", SqlDbType.VarChar, 250).Value = ad;
cmd.Parameters.Add("#hit", SqlDbType.DateTime).Value = hit;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
Write a method to insert data into data base and call that method after hidden fields get the data, then data automatically inserted into database.

saving form in database

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

Categories

Resources