CommandText property has not been initialized error in gridview - c#

I have a gridview and I want to checked line in insert but I see this error:
CommandText property has not been initialized.
I guess my mistake about strArrays. I'm working two days about it
How can I fixed?
StringBuilder stringBuilder = new StringBuilder(string.Empty);
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString.ToString());
SqlCommand sqlCommand = new SqlCommand();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
int type = 2;
CheckBox chkUpdate = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chkSelect");
TextBox txtAmount = (TextBox)GridView1.Rows[i].Cells[5].FindControl("txtAmount");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
string strID = GridView1.Rows[i].Cells[1].Text;
GridView1.Rows[i].FindControl("txtLocation")).Text;
string text = this.GridView1.Rows[i].Cells[1].Text;
string[] strArrays = new string[] { "INSERT INTO [OrderCancel]
([OrderID],
[Message],
[Type],
[RelationProductID],
[Amount])
VALUES(" ,
Request.QueryString["o"] ,
",'" , txtWhy.Text ,
"',",type.ToString(),",
" , strID , "," ,
txtAmount.Text , ");" };
stringBuilder.Append(string.Concat(strArrays));
//append update statement in stringBuilder
stringBuilder.Append(string.Concat(strArrays));
}
}
try
{
try
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = stringBuilder.ToString();
sqlCommand.Connection = sqlConnection;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
catch (SqlException sqlException)
{
throw new Exception(string.Concat("Error in Updation",
sqlException.Message));
}
}
finally
{
sqlConnection.Close();
}

Your code could be cleaned up, you could do the following:
private readonly string dbConnection = "...";
private const string query = "... Column = #Column";
For the sake of brevity I've added ... which will correlate to your Connection String and your query with parameters.
var message = String.Empty;
using(var connection = new SqlConnection(dbConnection))
using(var command = new SqlCommand(query, dbConnection))
{
connection.Open();
command.CommandType = CommandType.Text;
command.Parameters.Add("#Column", SqlDbType.NVarChar).Value = message;
command.ExecuteNonQuery();
}
So that small snippet would be inside of a method, which would pass a model of the data in your Grid. Then when you pass a value from your Grid, then you would build your model and pass to the method which will write to your database.
Also, when you use a StringBuilder you will also need to call ToString(); to ensure that it is a string rather than a StringBuilder when your utilizing.

This error usually happens if you do not set the commandText property. looking at your code it looks like your stringbuilder variable is not getting set. have you tried putting a breakpoint inside your "chkUpdate.Checked" loop? if yes, can you post the sql that gets constructed in your loop

Related

How to set sql parameters

I try that code for use sql parameters but didnt work and didnt return any error. How can I fix it?
string sql = "SELECT * FROM "+mw.db_name+".ananmez_genel Where hasta_id='#hastaid'";
string connectionString = ConfigurationManager.ConnectionStrings["MYDBConnectionString"].ConnectionString;
using (MySqlConnection connect = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(sql, connect))
{
connect.Open();
cmd.Parameters.AddWithValue("#hastaid",hasta_id);
MySqlDataReader mdr;
mdr = cmd.ExecuteReader();
if (mdr.Read())
{
for (int i = 0; i < 20; i++)
{
arti = (i + 1).ToString();
kontrol = mdr.GetString("c_" + arti);
if (kontrol == "True")
{
ananmezcheck.ananmez_gnlkontrol(i, check);
}
}
yirmibir.Text = mdr.GetString("txt_1");
}
connect.Close();
}
If i using just like that, it works:
string sql = "SELECT * FROM "+mw.db_name+".ananmez_genel Where hasta_id='"+hastaid+"'";
so there is no problem in the database.
This part is the problem:
Where hasta_id='#hastaid'
That's not using a parameter - that's searching for rows where the value of hasta_id is exactly the string #hastaid, because you've put it in a string literal. You need to get rid of the quotes:
Where hasta_id=#hastaid
Then it's looking for rows where the value of hasta_id matches the value of the parameter #hastaid.

An object reference is required for the non-static field, method, or property 'System.Data.Common.DbCommand.ExecuteScalar()'

I'm working with a local database in a Windows Form Application. It works like charm, but I wanted to check if a record that a user searchs for is in the dataBase. I wrote the following code, but I get an error and I can't figure out how to solve it. I know that I reference a non-static object to a static method. But didn't know how to solve it. Thank in advance !
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length != 0)
{
var connString = #"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
using (var conn = new SqlCeConnection(connString))
{
try
{
var numePrenume = textBox1.Text.Trim().Split(' ');
var nume = numePrenume[0];
var prenume = numePrenume[1];
conn.Open();
var query = "SELECT COUNT(*) FROM info WHERE Nume='" + nume + "' AND Prenume='" + prenume + "'";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
int userCount = (int) SqlCeCommand.ExecuteScalar();
if (userCount > 0)
{
Info form = new Info(nume, prenume);
form.Show();
}
else
{
MessageBox.Show("Nu exista un angajat cu acest nume");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Replace int userCount = (int) SqlCeCommand.ExecuteScalar(); with
int userCount = (int) command.ExecuteScalar();
because SqlCeCommand is a class and ExecuteScalar() is a non-static method of that class. so you cannot access ExecuteScalar() without a reference. in this statement var command = new SqlCeCommand(query, conn); you are creating a reference to that class so you can call ExecuteScalar() through this reference.
You need to use your SqlCeCommand object, not the class itself. Just change your
int userCount = (int)SqlCeCommand.ExecuteScalar();
to
int userCount = (int)command.ExecuteScalar();
A few things more;
You have an extra * after your COUNT(*). Remove it.
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your command and adapter automatically as you did for your connection.

how can i clear this error in c# programing

In this code every time ShenasehSamapel is two equal values I get an exception that says field ShenasehSamapel is not the primary key:
"The variable name '#ShenasehSamapel' has already been declared.
Variable names must be unique within a query batch or stored
procedure."
Here is the code that generates the error:
private void btnDefineNewKala_Click(object sender, EventArgs e)
{
if (txtShenasehSamapel.Text != "" & txtKalaName.Text != "")
{
//Anbar.FildArray[0]= txtRadif.Text;
Anbar.FildArray [1]= txtShenasehSamapel.Text;
Anbar.FildArray[2] =txtKalaName.Text;
string strDefineKala = "insert into AnbarFava.dbo.DefineKala (ShenasehSamapel ,KalaName )" +
" values ( #ShenasehSamapel , #KalaName )";
//Anbar.AnbarCMD.Parameters.AddWithValue("#Radif", Anbar.FildArray[0]);
Anbar.AnbarCMD.Parameters.AddWithValue("#ShenasehSamapel", Anbar.FildArray[1]);
Anbar.AnbarCMD.Parameters.AddWithValue("#KalaName", Anbar.FildArray[2]);
Anbar.RunQuery(strDefineKala);
for (int Element = 0; Element <= Anbar.FildArray.Length - 1; Element++)
{ Anbar.FildArray[Element] = null; }
//txtRadif.Text = " ";
txtShenasehSamapel.Text = "";
txtKalaName.Text = "";
/**/
string strcmd = "select * from AnbarFava.dbo.DefineKala";
SqlDataAdapter thisDataAdapter = new SqlDataAdapter(strcmd, Anbar.strCNN);
DataTable thisDataTable = new DataTable();
thisDataAdapter.Fill(thisDataTable);
dgvDefineKala.DataSource = thisDataTable;
}
else
{
MessageBox.Show("لطفا تمام خانه ها را پر کنید", "خطا",
MessageBoxButtons.OK); }
}
You are reusing connections and commands across function calls, you have a parameter from a previous call conflicting with your current call.
Anbar.AnbarCMD should not exist, you should create a new command each time. I also assume Anbar also holds a SqlConnection object, it should not be doing that either. All Anbar should hold is a connection string and a new connection and new command should be created each Click (Be sure to put the command and connection inside using statements so they get disposed)
I don't know exactly what RunQuery is doing but it could be rewritten to something similar to
public void RunQuery(string query, params SqlParameter[] parameters)
{
using(var connection = new SqlConnection(_connectionString)
using(var command = new SqlQuery(query, connection)
{
connection.Open();
command.Parameters.AddRange(parameters);
command.ExecuteNonQuery();
}
}
You then call it like so
var param1 = new SqlParameter("#ShenasehSamapel", Anbar.FildArray[1]);
var param2 = new SqlParameter("#KalaName", Anbar.FildArray[2]);
Anbar.RunQuery(strDefineKala, param1, param2);

Input string was not in a correct format

I'm trying to make a simple application form were user can input data like 'reservationid', 'bookid', 'EmployeeID' and 'reservedate'. Its from my program Library System. 'reservationid' is an auto increment primary key while the rest are BigInt50, NVarChar50 and DateTime10 respectively. So I'm having this error: Input String was not in a correct format. It worked fine a while ago until I modified the 'reservationid' to auto increment so where did I go wrong? I've attached a sample of my code behind.
Any help would be greatly appreciated! Thanks in advance!
namespace LibraryManagementSystemC4.User
{
public partial class Reserving : System.Web.UI.Page
{
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["LibrarySystemConnectionString"].ConnectionString;
}
//string reservationid
private void ExecuteInsert(string bookid, string EmployeeID, string reservedate)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO BookReservation (reservationid, bookid, EmployeeID, reservedate) VALUES " + " (#reservationid, #bookid, #EmployeeID, #reservedate)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
//param[0] = new SqlParameter("#reeservationid", SqlDbType.Int, 50);
param[0] = new SqlParameter("#bookid", SqlDbType.BigInt, 50);
param[1] = new SqlParameter("#EmployeeID", SqlDbType.NVarChar, 50);
param[2] = new SqlParameter("#reservedate", SqlDbType.DateTime, 10);
//param[0].Value = reservationid;
param[0].Value = bookid;
param[1].Value = EmployeeID;
param[2].Value = reservedate;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert error";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (reservationidTextBox != null)
{
//reservationidTextBox.Text
ExecuteInsert(bookidTextBox.Text, EmployeeIDTextBox.Text, reservationidTextBox.Text);
ClearControls(Page);
}
else
{
Response.Write("Please input ISBN");
bookidTextBox.Focus();
}
{
//get bookid from Book Details and Employee PIN from current logged-in user
bookidTextBox.Text = DetailsView1.SelectedValue.ToString();
EmployeeIDTextBox.Text = HttpContext.Current.User.Identity.ToString();
}
}
public static void ClearControls(Control Parent)
{
if (Parent is TextBox)
{
(Parent as TextBox).Text = string.Empty;
}
else
{
foreach (Control c in Parent.Controls)
ClearControls(c);
}
}
}
}
If reservationid is auto incremented then remove it from your insert query
string sql = "INSERT INTO BookReservation ( bookid, EmployeeID, reservedate) VALUES (#bookid, #EmployeeID, #reservedate)";
also try
param[0].Value = Convert.ToInt64(bookid);
param[1].Value = EmployeeID;
param[2].Value = Convert.ToDate(reservedate);
after you made reservationid to autoincrement then you dont have to do like
string sql = "INSERT INTO BookReservation (reservationid, bookid, EmployeeID, reservedate) VALUES " + " (#reservationid, #bookid, #EmployeeID, #reservedate)";
remove reservationid to insert.
do like
string sql = "INSERT INTO BookReservation ( bookid, EmployeeID, reservedate) VALUES (#bookid, #EmployeeID, #reservedate)";
Its because you are not passing the reservationid an Integer value to your command parameters when it is not Auto Increment.
I can see from your code, that you have declared string reservationid, but you are not assigning it any value and secondly it should an integer value.
I know this is deeply necro-posted, but since it seems from Loupi's comment on 9Jun11 that he was still having problems, I'd post the actual answer. Bala's answer was what was still giving him the Input Type is not in a correct format error; using a Convert.ToInt64 statement in a value assignation was tripping it. Do the conversion in variables previous to assigning the parameter values and it works a charm. The most likely culprit is that bookid was some sort of non-zero empty string representation (blank quotes, a space, null, whatever).
Edit: A quick and easy one-line test that's relatively bulletproof:
long numAccountNum = Int64.TryParse(AccountNum, out numAccountNum) ? Convert.ToInt64(AccountNum) : 0;

What's wrong with my IF statement?

I'm creating an auditting table, and I have the easy Insert and Delete auditting methods done. I'm a bit stuck on the Update method - I need to be able to get the current values in the database, the new values in the query parameters, and compare the two so I can input the old values and changed values into a table in the database.
Here is my code:
protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
string[] fields = null;
string fieldsstring = null;
string fieldID = e.Command.Parameters[5].Value.ToString();
System.Security.Principal. WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
string[] namearray = p.Identity.Name.Split('\\');
string name = namearray[1];
string queryStringupdatecheck = "SELECT VAXCode, Reference, CostCentre, Department, ReportingCategory FROM NominalCode WHERE ID = #ID";
string queryString = "INSERT INTO Audit (source, action, itemID, item, userid, timestamp) VALUES (#source, #action, #itemID, #item, #userid, #timestamp)";
using (SqlConnection connection = new SqlConnection("con string = deleted for privacy"))
{
SqlCommand commandCheck = new SqlCommand(queryStringupdatecheck, connection);
commandCheck.Parameters.AddWithValue("#ID", fieldID);
connection.Open();
SqlDataReader reader = commandCheck.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount - 1; i++)
{
if (reader[i].ToString() != e.Command.Parameters[i].Value.ToString())
{
fields[i] = e.Command.Parameters[i].Value.ToString() + "Old value: " + reader[i].ToString();
}
else
{
}
}
}
fieldsstring = String.Join(",", fields);
reader.Close();
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#source", "Nominal");
command.Parameters.AddWithValue("#action", "Update");
command.Parameters.AddWithValue("#itemID", fieldID);
command.Parameters.AddWithValue("#item", fieldsstring);
command.Parameters.AddWithValue("#userid", name);
command.Parameters.AddWithValue("#timestamp", DateTime.Now);
try
{
command.ExecuteNonQuery();
}
catch (Exception x)
{
Response.Write(x);
}
finally
{
connection.Close();
}
}
}
The issue I'm having is that the fields[] array is ALWAYS null. Even though the VS debug window shows that the e.Command.Parameter.Value[i] and the reader[i] are different, the fields variable seems like it's never input into.
Thanks
You never set your fields[] to anything else than null, so it is null when you are trying to access it. You need to create the array before you can assign values to it. Try:
SqlDataReader reader = commandCheck.ExecuteReader();
fields = new string[reader.FieldCount]
I don't really understand what your doing here, but if your auditing, why don't you just insert every change into your audit table along with a timestamp?
Do fields = new string[reader.FieldCount] so that you have an array to assign to. You're trying to write to null[0].

Categories