Check radiobuttons after SqlDataReader - c#

I have 2 radio buttons in a panel and I save their value as numeric (0 and 1) here is the code for insert into SQL:
String typdop="1";
if(rb_a.Checked)typdop="0";
("INSERT INTO zajezd(typdop)values(#typdop")
prikaz.Parameters.AddWithValue("typdop", typdop);
and for reading I use this:
SqlCommand novyprikaz = new SqlCommand("SELECT * FROM zajezd WHERE akce="+nc_zajezd_vyber, spojeni);
con.Open();
SqlDataReader precti = novyprikaz.ExecuteReader();
if (precti.Read())
{
try
{ rb_a.Checked = precti(32);}
the visual studio gives me an error, because I don't know how to change Checked value of rb_a, I would like to read it like this:
If in database is saved 0 - Check rb_a
If 1 I would like to check rb_b
May someone help solve this out?
Thanks

Too many details are missing, but you could try this code.
string cmdText = "SELECT * FROM zajezd WHERE akce=#p1";
SqlCommand novyprikaz = new SqlCommand(cmdText, spojeni);
novyprikaz.Parameters.AddWithValue("#p1", nc_zajezd_vyber);
spojeni.Open();
SqlDataReader precti = novyprikaz.ExecuteReader();
if (precti.Read())
{
try
{
bool check = Convert.ToBoolean(precti(32));
if(check)
rb_b.Checked = true;
else
rb_a.Checked = true;
}
}
Please take note; if your nc_zajezd_vyber is not of the correct datatype required by the database field, your query could fail to retrieve anything. AddWithValue assumes the datatype of the parameter from the value passed. If this is not correct....
For the same reasong (AddWithValue wants the exact datatype expected by the database field, then your insert code should be something like this:
int typdop=1;
if(rb_a.Checked) typdop=0;
string cmdText = "INSERT INTO zajezd(typdop)values(#typdop)";
SqlCommand prikaz = new SqlCommand(cmdText,spojeni);
prikaz.Parameters.AddWithValue("typdop", typdop);
spojeni.Open();
prikaz.ExecuteNonQuery();
....

Related

Using OleDDataReader to pull specific data from a database using a SQL command, C#

I am working on a project, where I want to use a SQL command string to sort through my database in ascending order according to one of the columns and then use another command to get the first value that is greater than or equal to a measured value.
For some reason or another my code only prints out 1, no matter what I change the value that is being measured against the database to. I'm not sure if there is an issue with my second SQL command string or if I am messing up with the OleDb Get methods.
I am a bit rusty with my programing so, additional advice would be appreciated.
Here is my code:
bool renew;
string conn = TableSettings.Instance.GetConnectionString();
string readingInDoubles = lblReading.Text;
double dNumber;
renew = Double.TryParse(readingInDoubles, out dNumber);
string SqlCmdSort = "SELECT * FROM Tables ORDER BY Mass ASC";
string SqlCmdCompare = "SELECT * FROM Tabels WHERE Mass >= " + renew;
using (OleDbConnection connect = new OleDbConnection(conn))
{
OleDbCommand command = new OleDbCommand(SqlCmdSort, connect);
OleDbCommand command2 = new OleDbCommand(SqlCmdCompare, connect);
connect.Open();
OleDbDataReader sort = command.ExecuteReader();
while (sort.Read())
{
OleDbDataReader compare = command2.ExecuteReader();
compare.Read();
// compare.GetDouble(0); ignore this.
lblUpperValue.Text = compare[0].ToString();
compare.Close();
}
sort.Close();
connect.Close();
}

How to add to an Update statement

I am trying to update my database(Table) and make the active column = 1.
I have duplicate reports (subject_text) with different countries and parameters.
subject_text countries parameter1 active
usage GB 1 0
usage FR 2 0
usage PT 1 0
closed GB,FR,PT 1 0
Here is an example of what my database looks like(simplified, there are many more parameters and many more reports but i hope you can see what I mean by duplicate report names)
Here is my .cs file to show the update i am trying to carry out.The Subject_text are in drop-down list form so the user can select which report to update. These reports(subject_text) are hard-coded into my ASPX page. When selecting a report such as 'closed' the update works, but when it comes to updating reports which have different countries or parameters that where i'm having trouble.
Masterpage masteris linking this page to where the .getDropDownListValue is
How can I add to my update statement when the drop-down lists contain different elements?
protected void RunReport_Click (object sender, System.EventArgs e)
{
MasterPage master = (MasterPage)this.Master;
string sqlStatement = "";
sqlStatement = #"UPDATE [TODD].[dbo].[Table] SET Active='1' WHERE subject_text = #report";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sqlStatement, conn);
cmd = new SqlCommand(sqlStatement, conn);
cmd.Parameters.AddWithValue("#report", ddl_Report.SelectedItem.Text);
string getcountry = master.getDropDownListValue(ddl_country, false);
if (!string.IsNullOrWhiteSpace(getcountry))
{
cmd.Parameters.AddWithValue("#country", getcountry);
sqlStatement += "AND countries = #country";
}
string getparam1 = master.getDropDownListValue(Param1, false);
if (!string.IsNullOrWhiteSpace(getparam1))
{
cmd.Parameters.AddWithValue("#param1", getparam1);
sqlStatement += "AND parameter1 = #param1";
}
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Thank you for your time.
move
SqlCommand cmd = new SqlCommand(sqlStatement, conn);
to below the final calculation of your string sqlStatement
adding new text to sqlStatement should be done before you create your SqlCommand based on sqlStatement
also, you do not need to call new SqlCommand(sqlStatement, conn); twice
Why don't you just pass the identity? This is much cleaner.
UPDATE [TODD].[dbo].[Table] SET Active='1' WHERE RecordID = #RecordId

Sql Conversion from nVarchar to int error

Error:
Conversion failed when converting the nvarchar value 'select TopicID from Topic where TopicName='Data Structure'' to data type int
Code:
public void BindGridview()
{
string strConnString = ConfigurationManager.ConnectionStrings["infoConnectionString"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(strConnString);
sqlcon.Open();
string strquery2 = "select TopicID from Topic where TopicName='" + ddltopic.SelectedItem.Text+ "'";
string strquery3 = "select i.name ,i.score from info as i,Topic as t where i.topic_id=#topicid";
SqlCommand cmd = new SqlCommand(strquery3,sqlcon);
cmd.Parameters.AddWithValue("#topicid",strquery2);
cmd.Connection = sqlcon;
SqlDataReader dr;;
this.GridView1.DataSource =cmd.ExecuteReader();
this.GridView1.DataBind();
sqlcon.Close();
}
}
Could anyone tell me where I am going wrong? Any help would be appreciated.. Please reply as soon as possible.. Thanks in advance..
You are passing the in the entire query not the topic id in this line here
cmd.Parameters.AddWithValue("#topicid",strquery2);
It is then taking that as a parameter and adding it to the following query. If this is a subquery, you can always execute it first and then use the result in the paramter.
But the reason that it is failing is because you are essentially trying to compare a String to an int by passing in the query string like that.
I think what you want in cmd.Parameters.AddWithValue("#topicid",strquery2); is the value returned by strquery2???? , the topic id will get generated if you execute this query first and the result of this will be used instead of query itself
Is that what you want ??
can you tried with below code, I have not tested but its should work for you
public void BindGridview()
{
string strConnString = ConfigurationManager.ConnectionStrings["infoConnectionString"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(strConnString);
sqlcon.Open();
//Equal is not working when subquery return more records
string strquery2 = "select i.name ,i.score from info as i,Topic as t where i.topic_id in (select TopicID from Topic where TopicName=#TopicName)";
SqlCommand cmd = new SqlCommand(strquery2, sqlcon);
cmd.Parameters.AddWithValue("#TopicName", ddltopic.SelectedItem.Text);
cmd.Connection = sqlcon;
SqlDataReader dr; ;
this.GridView1.DataSource =cmd.ExecuteReader();
this.GridView1.DataBind();
sqlcon.Close();
}
Not an actual answer, but comments are too short for this.
This code is vulnerable to SQL injection:
string strquery2 = "select TopicID from Topic where TopicName='" + ddltopic.SelectedItem.Text+ "'";
Imagine that at some point in the future someone (you or someone else who is modifying your code) decides to replace the drop-down list with a combo box? Now imagine someone enters this text into the combo box:
'; TRUNCATE TABLE Topic; --'
Now your SQL server is going to do this:
select TopicID from Topic where TopicName = '';
TRUNCATE TABLE Topic; --'
Learn to use parameters.

C# No value given for 1 or more required parameters, but I can't see why

I have posted the code I have below
I am trying to get the data from an Access 2002-2003 database
If I take out everything after the WHERE clause and just use "SELECT * FROM [{0}] then it takes all the data from the table with no problems. I have double checked the field names, they are definitely correct. I have more than 1 table with the same field names, so I thought maybe I would need to include the table name before the field name, but with or without the table I still get the same exception. I have tried moving the position of the square brackets, again with no success...
Even if I include only one of the WHERE clauses, the code no longer works, and I can't for the life of me work out why.. I have spent hours looking at numerous posts here and on other sites related to this error, but none of the suggestions have helped me..
The Destination field is a 'memo' field in Access.
The Next Collection fields are date fields, GVars.currentDate is set earlier in the code to be today's date (with the time portion set to 00:00:00).
GVars.thisFY is also set programatically as a string prior to this.
Any tips would be appreciated.
string sql;
OleDbDataAdapter adapter;
sql = string.Format(
"SELECT * FROM [{0}] WHERE {0}.[Destination] = #Destination AND {0}.[Next Collection] BETWEEN #NextCollectionA AND #NextCollectionB"
, GVars.thisFY);
// Create the command object
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
// Add values to the fields
cmd.Parameters.AddWithValue("#Destination", "Henwood");
cmd.Parameters.AddWithValue("#NextCollectionA", GVars.currentDate);
cmd.Parameters.AddWithValue("#NextCollectionB", GVars.currentDate.AddDays(1));
adapter = new OleDbDataAdapter(cmd.CommandText, conn);
System.Diagnostics.Debug.Print(cmd.CommandText);
try
{
adapter.Fill(ds);
GVars.bLblLastUpdate = DateTime.Now.ToString("HH:mm:ss");
}
catch (Exception ex)
{
}
EDIT:
Thanks Vladislav for the answer, corrected code posted below:
string sql;
OleDbDataAdapter adapter;
sql = string.Format(
"SELECT * FROM [{0}] WHERE [{0}].[Destination] = #Destination AND [{0}].[Next Collection] BETWEEN #NextCollectionA AND #NextCollectionB"
, GVars.thisFY);
// Create the command object
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = conn;
// Add values to the fields
cmd.Parameters.Add("#Destination", OleDbType.Char).Value = "Henwood";
cmd.Parameters.Add("#NextCollectionA", OleDbType.DBDate).Value = GVars.currentDate;
cmd.Parameters.Add("#NextCollectionB", OleDbType.DBDate).Value = GVars.currentDate.AddDays(1);
adapter = new OleDbDataAdapter(cmd);
try
{
adapter.Fill(ds);
GVars.bLblLastUpdate = DateTime.Now.ToString("HH:mm:ss");
}
Try to specify types for the parameters you add.
Another thing I notice is that to your adapter you are passing only the CommandText.
You should pass the whole command object.

Is this query to retrieve data from database correct?

I need to retrieve a value from a field in database. I have the used following code. but the value checkOrderId (which I need) shows the SQL string instead of the value from database. I don't know why it is doing so. Could somebody help me please?
string connectionString = "Data Source = xxyyzz;Initial Catalog = xyz; Integrated Security = True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From" + tableName + "ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
//cmd.ExecuteNonQuery();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == checkOrderId)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
I am new and dont have reputation to answer my question immediately. With everybody's help, i got this one solved...Great help, thanx everybody...following is my code.
string connectionString = "Data Source = EAEDEV;Initial Catalog = GIS; Integrated Security = True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
string valueReturned = (string)cmd.ExecuteScalar();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == valueReturned)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
}
You need to execute the query and check the results, here you are just comparing a string with the query SQL.
Please see here
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson03
for a tutorial.
Your expectation of the result being set into checkOrderId is incorrect. In this instance checkOrderId is just the query to execute and not the actual result.
You need to read the value back from executing the command:
using (var connection = new SqlConnection(connectionString))
using (var comm = new SqlCommand("Select TOP 1 OrderID From [GIS].[SecondaryTraffic].[PotentialBackHauls] ORDER BY InsertDate DESC", connection))
{
connection.Open();
object result = comm.ExecuteScalar(); // This is the key bit you were missing.
if (result != null)
{
// You can cast result to something useful
int orderId = (int)result;
}
} // Both comm and connection will have Dispose called on them here, no need to Close manually.
ExecuteScalar returns the value in the first cell (ie, column 1 row 1) as an object that you can cast to a better type (depending on what type it was in the result-set schema).
If you need to read multiple values, you need to look at ExecuteReader.
There are also other ways of doing this using output parameters, but that would pollute the point of the answer.
You can add space to your query
"Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
Nota : I suggest you to use AddWithValue method with your parameter
string checkOrderId = "Select TOP 1 OrderID From #tableName ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
cmd.Parameters.AddWithValue("#tableName", tableName );
Link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
You don't actually run your command anywhere. Instead of the commented-out cmd.ExecuteNonQuery, you should look into the ExecuteScalar method, which allows you to read back a single result value from a query - which is what your query returns.
Add
int i = (Int32) cmd.ExecuteScalar();
right after
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
then the variable i will contain the order id
No, this is not correct. You are comparing the variable orderId to your query string. I doubt that's what you want to do. I imagine you'd be better off calling cmd.ExecuteScalar() to retrieve the actual OrderID value. As noted by other answers, your query string is missing a space. But most importantly, it is bad practice to construct SQL queries in code. Although I can't see a security issue with this code, if you continue to use this method you will probably write code that is vulnerable to SQL injection. I recommend you learn to either use parameters or LINQ to build your queries.

Categories

Resources