If i find the 3 "Yes" in my table for a given ID then i am sending an email. So as you can see the code below is using the querystring as parameter and using that in my select statement but what i want to do is use the selected ID in the DetailView instead of the query-string. Here is the code that uses the query-sting:
protected void Check_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT count(*) from MyTable WHERE ID =#ID And (field1='Yes' And field2='Yes' And field3='Yes')", con);
cmd.Parameters.Add("#ID", Request.QueryString["ID"]);
cmd.Connection = con;
con.Open();
int result = (int)cmd.ExecuteScalar();
if (result == 1)
{
send email...
}
and here is the updated code that i modified and tried to use the DetailView ID but does not work properly, what am i doing wrong here pls help:
protected void Check_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
string ID = Detailview1.Rows[0].Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT count(*) from MyTable WHERE ID =#ID And (field1='Yes' And field2='Yes' And field3='Yes')", con);
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID;
cmd.Connection = con;
con.Open();
int result =(int) cmd.ExecuteScalar();
if (result == 1)
{
send email...
}
Looks like you are always looking same row which is the header in most of the case.
string ID = Detailview1.Rows[0].Cells[1].Text;
Instead of this you should use parameters of the event like e if you set every thing correctly you can get the ID by e.Keys. You can check the value of it in debug mode.
Related
Below here is my code to Retrieve Auto Increment ID After Inserting data into database.
However, I am getting Auto Increment ID before Inserting data into database.
How can I get auto increment ID after insert into database?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RetrievePRReqID();
}
}
//Retrieve ID method
private void RetrievePRReqID()
{
try
{
string query = "Select IDENT_CURRENT('tblPRRequest')";
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand cmd = new SqlCommand(query, sqlCon);
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
int value = int.Parse(reader[0].ToString()) ;
txt_PRNO.Text = value.ToString();
}
}
catch(Exception)
{
throw;
}
finally
{
if(con.State == ConnectionState.Open)
{
con.Close();
}
}
}
//Request button Method
protected void btn_Request(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.Clear();
SqlCommand sqlCmd = new SqlCommand(insertCmd, sqlCon);
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
sqlcmd.ExecuteNonQuery();
}
}
***//After Insert into the table, I want to retrieve latest generated Auto Increment ID in here.***
}
By referring sample answer from #Mx.Wolf, I modified a bit to get the right answer, below here is the codes that is working :
protected void btn_Request(object sender, EventArgs e)
{
object id ;
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"output inserted.PRReqID " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
id = sqlcmd.ExecuteScalar(); //the result is of Object type, cast it safely
}
}
Debug.WriteLine(id.ToString()); // Access it like this
As stated in SQL Server documentation
https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-ver15
The OUTPUT clause may be useful to retrieve the value of identity or computed columns after an INSERT or UPDATE operation.
You have to change your SQL statement
INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName)
OUTPUT inserted.ID
-------^^^^^^^^_^^
VALUES (#RequestTo,#RequestFrom,#RequestedByName)
and now you can use ExecuteScalar to get the inserted value
protected void btn_Request(object sender, EventArgs e)
{
int id= 0;
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"output inserted.ID" +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
id = (int)sqlcmd.ExecuteScalar(); //the result is of Object type, cast it safely
}
}
Debug.WriteLine(id.ToString()); // Access it like this
}
Try this:
protected void btn_Request(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.Clear();
SqlCommand sqlCmd = new SqlCommand(insertCmd, sqlCon);
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
sqlcmd.Parameters.Add("#ID", SqlDbType.Int).Direction = ParameterDirection.Output;
sqlcmd.ExecuteNonQuery();
}
}
***//After Insert into the table, I want to retrieve latest generated Auto Increment ID in here.***
sqlcmd.Parameters["#ID"].value; // Access it like this
}
In case you can chage the ExecuteNonQuery to ExecuteScalar, then it would be even easier: What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?
I am making a basic web form with basic fields like name, email, number.
I just want, when i enter the number, rest of the fields are populated in the other textboxes based on that number from sql server.
Any help would be appreciated.
Code is as follows :
string ConnectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
string cmd = "IF NOT EXISTS(Select * from tbl_registration where Email = #Email OR MobileNo = #MobileNo) insert into tbl_registration values(#FirstName, #LastName,#Email,#MobileNo,#Address_1,#Address_2,#City,#State)";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using(SqlCommand com = new SqlCommand(cmd, con))
{
com.Parameters.AddWithValue("#FirstName", txtfname.Text.Trim());
com.Parameters.AddWithValue("#LastName", txtlname.Text);
com.Parameters.AddWithValue("#Email", txtemail.Text);
com.Parameters.AddWithValue("#MobileNo", txtmob_no.Text);
com.Parameters.AddWithValue("#Address_1", txtaddress1.Text);
com.Parameters.AddWithValue("#Address_2", txtaddress2.Text);
com.Parameters.AddWithValue("#City", txtcity.Text);
com.Parameters.AddWithValue("#State", txtstate.Text);
con.Open();
int success = com.ExecuteNonQuery();
if (success > 0)
{
Response.Write("<script>alert('Registration successfull')</script>");
}
else
{
Response.Write("<script>alert('Registration Not Sucessfull')</script>");
}
}
}
}
You should write the method definition as shown below on the text box changed event.
This is not the complete query answer. Here is a reference for you.
using (SqlConnection conn = new SqlConnection(CSs))
{
string query = "Your SQL Query here";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "sometablename");
firstnametext.Text = Convert.ToString(ds.Tables["sometablename"].Rows[0]["Firstname"]);
}
Here you need to properly handle the null for the data table.
I am using windows forms C# and SQL. I have a table consists of two column:
Column1 = myID (primary key and unique ID)
Column2 = DateTime.
The following code inserts date/Time into the table:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
cn.Open();
SqlCommand cm = new SqlCommand("Insert into TableDate_Time (DateTime ) values (#DateTime)");
cm.Parameters.Add("#DateTime", SqlDbType.DateTime);
cm.Parameters["#DateTime"].Value = DateTime.Now;
cm.Connection = cn;
cm.ExecuteNonQuery();
// something like: var varID = the current myID value
}
My Question is: How can I save the last row value of myID column into a variable whenever I click the button? any idea? Thank you
In Sql Server (and other database systems) you could pass two commands in the same text. Now T-SQL allows you to get back the last IDENTITY value generated for your connection using the command "SELECT SCOPE_IDENTITY()".
Thus your code will be
private void button1_Click(object sender, EventArgs e)
{
string cmdText = #"Insert into TableDate_Time
(DateTime ) values (#DateTime);
SELECT SCOPE_IDENTITY()");
using(SqlConnection cn = new SqlConnection("...."))
using(SqlCommand cm = new SqlCommand(cmdText, cn))
{
cn.Open();
cm.Parameters.Add("#DateTime", SqlDbType.DateTime);
cm.Parameters["#DateTime"].Value = DateTime.Now;
int id = Convert.ToInt32(cm.ExecuteScalar());
....
}
}
Instead of ExecuteNonQuery, call ExecuteScalar that returns the first column of the first row in the last command executed here (The SELECT). Note that it is a good practice to enclose every disposable object like the connection and the command in a using statement to have a correct exit path for your code in case of exceptions (one that doesn't forget to dispose these objects)
EDIT
If your ID column is not an IDENTITY column but an uniqueidentifier there are more problems. I suppose that your table has defined a default for the column ID using the NEWID() function of T-SQL
In this case you need to change your query to
private void button1_Click(object sender, EventArgs e)
{
string cmdText = #"Insert into TableDate_Time
(DateTime ) OUTPUT INSERTED.myID values (#DateTime)";
using(SqlConnection cn = new SqlConnection("...."))
using(SqlCommand cm = new SqlCommand(cmdText, cn))
{
cn.Open();
cm.Parameters.Add("#DateTime", SqlDbType.DateTime);
cm.Parameters["#DateTime"].Value = DateTime.Now;
Guid id = (Guid)cm.ExecuteScalar();
....
}
}
Assuming that the new ID is generated in the database via a column default, you could use the OUTPUT clause to return the ID of the new record:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
cn.Open();
SqlCommand cm = new SqlCommand("INSERT INTO TableDate_Time (DateTime) OUTPUT inserted.myID VALUES (#DateTime)");
cm.Parameters.Add("#DateTime", SqlDbType.DateTime);
cm.Parameters["#DateTime"].Value = DateTime.Now;
cm.Connection = cn;
Guid newID = (Guid)cm.ExecuteScalar();
}
Some other things to consider that are not germane you your problem:
Don't put direct SQL logic in a button click event handler - use a separate class for data management
Wrap you commands and connections in using blocks so that they are closed in a timely fashion, even if there is an exception.
That's easy. Just add the following code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
cn.Open();
SqlCommand cm = new SqlCommand("Insert into TableDate_Time (DateTime ) values (#DateTime)");
cm.Parameters.Add("#DateTime", SqlDbType.DateTime);
cm.Parameters["#DateTime"].Value = DateTime.Now;
cm.Connection = cn;
int returnValue = 0;
SqlParameter param = new SqlParameter();
param.ParameterName = "ReturnParameter";
param.Direction = ParameterDirection.ReturnValue;
cm.Parameters.Add(param);
cm.Connection.Open();
cm.ExecuteNonQuery();
}
And in your stored procedure (or sql query) add:
DECLARE #ID int = (Select SCOPE_IDENTITY())
RETURN #ID
I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}
i am using asp.net C# SQL to create a webpage.I need to list out a courseID to let user choose, but it list out two time same value in dropdownlist
S1111
S2222
S3333
S1111
S2222
S3333
,someone help
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn;
SqlDataReader dtr;
SqlCommand cmd;
string Connnection = ConfigurationManager.ConnectionStrings["ELearing"].ConnectionString;
conn = new SqlConnection(Connnection);
if (!Page.IsPostBack)
{
//Get Staff Information
conn.Open();
string cmdString = "SELECT DISTINCT CourseID FROM Schedule WHERE(StaffID = #scheduleStaffID)";
cmd = new SqlCommand(cmdString, conn);
cmd.Parameters.AddWithValue("#scheduleStaffID", Session["UserID"].ToString());
dtr = cmd.ExecuteReader();
while (dtr.Read())
{
ddlCourse.Items.Add(dtr["CourseID"].ToString());
}
dtr.Close();
conn.Close();
}
}
Try these
1.Do you get duplicates when you do externally SELECT DISTINCT CourseID FROM Schedule WHERE StaffId = 1
2.use breakpoints to check additional post backs.
3.Try ddlCourse.Items.Clear just before your while loop.