What is wrong with this code? I want to catch the last value from SQL row and display it in a TextBox. Kindly help me.
private void textBox2_Leave(object sender, EventArgs e)
{
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select last(remain) from item_new_customer where cust=" + textBox2.Text + "";
float h = (float)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
cmd.CommandText = "select max(remain) from item_new_customer where cust='" + textBox2.Text + "'";
You are open for SQL-Injection, use parameters to avoid it.
To answer your actual question, i assume that you want this column: remain. But you want the value of the last inserted record. Since you haven't mentioned the column to detect the order of insertion, i use the primary key column (not recommended):
string sql = "SELECT TOP 1 remain FROM dbo.tablename WHERE cust=#cust ORDER BY id DESC";
using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#cust", textBox2.Text);
con.Open();
double h = (double)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
You're missing a single quote after the textBox2.Text:
private void textBox2_Leave(object sender, EventArgs e)
{
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"select max(remain) from item_new_customer where cust=" + textBox2.Text + "'";
//Missing tick here ^
float h = (float)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
In addition, your code is an open invitation for SQL injection.
Thanks very much for all
My final right code is:
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select top 1(remain) from item_new_customer where cust='"+textBox2.Text+"' order by id desc";
int h = (int)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
What I would just do is put all of the SQL row values into a listbox and then take the text of the last item in the textbox and put that into a textbox. Keep the listbox hidden
private System.Windows.Forms.ListBox listBox1;
static SqlConnection connection = new SqlConnection(#"Data Source=hostname;Initial Catalog=database_name;Integrated Security=False;User ID=user;Password=123456;");
SqlDataAdapter adapter = new SqlDataAdapter("select * from table_name", connection);
DataTable table = new DataTable();
adapter.Fill(table);
foreach (DataRow row in table.Rows)
{
listBox1.Items.Add(row["row_name"].ToString());
}
textBox20.Text = listBox1.Items[listBox1.Items.Count - 1].ToString();
Related
In the code below, i just want to fill my textbox based on the selected combo box changed. but i get the following error.
'Conversion failed when converting the varchar value
'System.Data.DataRowViewConvert.ToString()' to data type int.'
i'd appreciate it if you help me.
SqlConnection objConnection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\UniversityDataBase.mdf;Integrated Security=True");
private void comboBox1_Click(object sender, EventArgs e)
{
string query = "SELECT *FROM TutorTable";
SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
DataTable dt = new DataTable();
SDA.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Tid";
objConnection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sqlQuery = "SELECT *FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'";
SqlCommand objCommand = new SqlCommand(sqlQuery, objConnection);
objConnection.Open();
objCommand.ExecuteNonQuery();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string Tname = (string)dr["Tname"].ToString();
textBox1.Text = Tname;
}
}
Why are you using the Convert.ToString() in this piece of code:
"SELECT * FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'"
I think the correct way wolud be:
"SELECT * FROM TutorTable where Tid = '"+comboBox1.Text+ "'"
But consider using a store procedure to prevent sql injection or using an ORM.
I think that comboBox1.Text is already returning a string value. So if that, it is not necessary to put the Convert.ToString(comboBox.Text), just put comboBox1.Text
According to documentation, the Text property is a string
https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.text(v=vs.110).aspx
I found the Solution as follows:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\UniversityDataBase.mdf;Integrated Security=True");
string sqlQuery = "SELECT *FROM TutorTable WHERE Tid = '" + comboBox1.Text + "'";
SqlCommand objCommand = new SqlCommand(sqlQuery, con);
con.Open();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string name = (string)dr["Tname"].ToString();
textBox1.Text = name;
}
}
You have got the answer already but few more things should be taken care of
Your code
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sqlQuery = "SELECT *FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'";
SqlCommand objCommand = new SqlCommand(sqlQuery, objConnection);
objConnection.Open();
objCommand.ExecuteNonQuery();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string Tname = (string)dr["Tname"].ToString();
textBox1.Text = Tname;
}
}
Things to notice:
1) Use varabled instead of manipulating sql
e.g. SELECT *FROM TutorTable where Tid = #id and pass id into sqlCommand object
2) You dont need to call ExecuteNonQuery before SqlDataReader
3) you need to use if(dr.Read()) instead of while
4) You can directly assign value textbox.
e.g. texBox1.Text = dr["Tname"].ToString();
5) Close the objConnection
I have written following code.
my 1st orderid has both records for process 1 and process 2
but my 2nd orderid has record only for process 1.
when i select orderid 2 after selecting orderid 1 it keeps the value as it is for orderid 1 in process 2 textbox.
i want that textbox to be blank
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DbConnect objdbc = new DbConnect();
SqlConnection con = objdbc.openConnection();
SqlCommand cmd = new SqlCommand("SELECT [orderid],[processid],[orgid],[processdesc] ,[perwet] FROM [anghan].[dbo].[ProcessOrder] where orderid='" + DropDownList1.SelectedItem.Value + "' and processid=1 ", con);
cmd.CommandType = CommandType.Text;
// cmd.Parameters.AddWithValue("#Id", value);
cmd.Connection = con;
//con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
TextBox2.Text = dr["perwet"].ToString();
// DropDownList1.Items(DropDownList1.SelectedIndex).Text = dr["service"].ToString();
}
dr.Close();
//process 2
SqlCommand cmd2 = new SqlCommand("SELECT [orderid],[processid],[orgid],[processdesc] ,[perwet] FROM [anghan].[dbo].[ProcessOrder] where orderid='" + DropDownList1.SelectedItem.Value + "' and processid=2 ", con);
cmd2.CommandType = CommandType.Text;
// cmd.Parameters.AddWithValue("#Id", value);
cmd2.Connection = con;
//con.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
TextBox3.Text = dr2["perwet"].ToString();
// DropDownList1.Items(DropDownList1.SelectedIndex).Text = dr["service"].ToString();
}
dr2.Close();
Why do not you set the TextBox2 and TextBox3 to empty in the starting of the code . So that you do see what you have populated . Only those textbox value will be change where your code will reassign otherwise it will keep the old value.
just put like this>>
if(dr!=null)
{
while (dr.Read())
{
if((dr["perwet"]!=null)||(dr["perwet"].ToString()!=""))
TextBox2.Text = dr["perwet"].ToString();
else
TextBox2.Text="";
// DropDownList1.Items(DropDownList1.SelectedIndex).Text = dr["service"].ToString();
}
}
It will work.
We have selected a value from a combobox and need the related information in the textbox.
The following code does not work for the same.
private void itemcode_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = (string)itemcode.SelectedItem;
SqlConnection conn3 = new SqlConnection(connString);
conn3.Open();
//For Redundency Checking Code of Supplier id.
string iname = "select Itemname from Items where Itemcode='" +
itemcode.SelectedItem.ToString() + "'";
SqlCommand cmdRedun1 = new SqlCommand(iname, conn3);
SqlDataReader dr1 = cmdRedun1.ExecuteReader();
dr1.Read();
itemname.Text = dr1["Itemname"].ToString();
dr1.Close();
}
First Check your Item Value Of Combo box , and then create your query with StringFormat
for example :
string iname = String.Format("select Itemname from Items where Itemcode='{0}'",
itemcode.SelectedItem.ToString()) ;
//-- then please check out below code :
SqlConnection SqlConn = new SqlConnection(this.ConnectionString);
SqlConn.Open();
SqlCommand SqlCmd = new SqlCommand(" Your Select....", SqlConn);
SqlCmd.CommandType = CommandType.Text;
SqlDataReader r = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
//----need this
while (r.Read())
itemname.Text = string.IsNullOrEmpty(r["Itemname"].ToString()) ?
string.Empty : r["Itemname"].ToString();
r.Close();
if (SqlConn.State != ConnectionState.Closed)
SqlConn.Close();
You can try ExecuteScalar instead of SqlDataReader.
I got 2 comboboxes on my form(in the form load event). First combobox gets a value from a select statement once the form loads. I want to use that value in my second combobox. Here is my code:
1ste Combobox = cbDelivery
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "User Id=christob;Password=CHRISTOB;Host=poseidon;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;Port=1522;Sid=GLODCD";
conn.Open();
string query;
query = "select distinct dd.delivery_bay_code from dc_delivery dd, dc_grv dg where delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbDelivery.Items.Add(dr["delivery_bay_code"]);
}
dr.Close();
conn.Close();
2de Combobox = cbOrderNo
This combobox is in:
private void cbDelivery_SelectedIndexChanged(object sender, EventArgs
e)
so as soon as I select a value from 1ste combobox my 2nd combobox query must populate the 2nd combobox. See code:
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "User Id=christob;Password=CHRISTOB;Host=poseidon;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;Port=1522;Sid=GLODCD";
conn.Open();
string query1;
query1 = "select distinct dg.order_no from dc_delivery dd, dc_grv dg where delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null and dd.delivery_bay_code = " + cbDelivery.Text;
OracleCommand cmd1 = new OracleCommand(query1, conn);
OracleDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
cbOderNo.Items.Add(dr1["order_no"]);
}
dr1.Close();
conn.Close();
Note I'm using cbDelivery combobox in my second Select query.
Problem is:
As soon as I select a value from my first combobox the second gives an exception ""ORA-00904: "BAY1": Invalid Identifier.
Please help me sort this out or suggest a different method.
Thanks in Advance.
May be your query using some keyword of sql or oracle as column name or at some invalid place. in such cases this type of errors are possible. I am not sure about this solution. but atleast we can try once. so that we can make it sure if its correct or not?
FIXED!! This is how i did it:
private void populateDeliveryBayCodes()
{
conn.Open();
string query;
query = "select distinct dd.delivery_bay_code from dc_delivery dd, dc_grv dg where dd.delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbDelivery.Items.Add(dr["delivery_bay_code"]);
}
dr.Close();
conn.Close();
}
private void populateOrderNumbers()
{
conn.Open();
string query;
query = "select distinct dg.order_no from dc_delivery dd, dc_grv dg where dd.delivery_complete_datetime is null and dd.dc_delivery_id_no = dg.dc_delivery_id_no and dd.delivery_announce_datetime is null and dd.delivery_bay_code ='" + cbDelivery.Text + "' order by order_no";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbOderNo.Items.Add(dr["order_no"]);
}
dr.Close();
conn.Close();
}
and
private void frmBuiltPallet_Load(object sender, EventArgs e)
{
populateDeliveryBayCodes();
{
private void cbDelivery_SelectedIndexChanged(object sender, EventArgs e)
{
populateOrderNumbers();
}
I have a gridview that has and auto- generated delete button. The grid has one datakeyname and for some reason it I am getting this error : Message: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
I have looked at many tutorials and examples. This code should work right?
protected void grdBins_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rec_id = int.Parse(grdBins.DataKeys[e.RowIndex].Value.ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from t_run_schedule_lots " +
"where rec_id = #id";
cmd.Parameters.Add("#id", SqlDbType.Int).Value = rec_id ;
cmd.CommandType = CommandType.Text;
cmd.Connection = this.sqlConnection1;
this.sqlConnection1.Open();
//execute insert statement
cmd.ExecuteNonQuery();
this.sqlConnection1.Close();
//re-populate grid */
fill_grid();
grdBins.EditIndex = -1;
grdBins.DataBind();
// this bit was just to see if I was capturing the ID field properly.
lblBins.Visible = true;
lblBins.Text = rec_id.ToString();
}
If anyone knows a good example in C# that would make this work it would be greatly appreciated.
I might be misunderstanding your question but according to here the EditIndex property is zero-based so you can't set it to -1. Setting it to that value will throw an ArgumentOutOfRangeException.
Here is what I did to get it working:
GridViewRow row = (GridViewRow)grdBins.Rows[e.RowIndex];
Label id = (Label)row.FindControl("Label9");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from t_run_schedule_lots " +
"where rec_id = #id";
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(id.Text) ;
Although I don't know why the RowIndex option would not work. Anyway it is working now.
Sounds like you don't have the DataKeyNames="rec_id" in the gridview aspx set?
cant get to datakeys if you haven't let the page know what they are
this is a refactored version of your code.
protected void grdBins_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rec_id = int.Parse(grdBins.DataKeys[e.RowIndex].Value.ToString());
using (SqlConnection conn = new SqlConnection(connectionString)){
conn.Open();
string cmdText = #"delete from t_run_schedule_lots
where rec_id = #id";
using (SqlCommand cmd = new SqlCommand(cmdText, conn)){
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#id", rec_id);
cmd.ExecuteNonQuery();
}
}
grd.EditIndex = -1;
fill_grid();
grdBins.DataBind();
}