DataTable is not getting the data requested - c#

I ran the SQL Query in SQL Server Management Studio and it worked.
I get the following error in my WinForm C# application
The parameterized query '(#word1 text)SELECT distinct [database].[dbo].[tableName].[n' expects the parameter '#word1', which was not supplied.
Here is my code
private void buttonRunQuery_Click(object sender, EventArgs e)
{
if (connection == null)
{
connection = ConnectionStateToSQLServer();
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
else
{
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
}
private SqlCommand createSQLQuery(SqlCommand command)
{
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [database].[dbo].[customerTable].[name], [database].[dbo].[customerTable].[dos], [database].[dbo].[customerTable].[accountID], [database].[dbo].[reportTable].[customerID], [database].[dbo].[reportTable].[accountID], [database].[dbo].[reportTable].[fullreport] FROM [database].[dbo].[reportTable], [database].[dbo].[customerTable] WHERE ";
int i = 1;
foreach (string word in allTheseWords)
{
var name = "#word" + (i++).ToString();
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
SQLQuery = SQLQuery + String.Format(" [database].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
}
SQLQuery = SQLQuery + " [database].[dbo].[customerTable].[accountID] = [database].[dbo].[reportTable].[accountID]";
command.CommandText = SQLQuery;
}
MessageBox.Show(command.CommandText.ToString());
return command;
}
public DataTable GetData(SqlCommand cmd)
{
//SqlConnection con = new SqlConnection(connString);
//SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
connection.Open();
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
return dt;
}
The error is happening on da.Fill(dt)
Any suggestions would be helpful
Thank you

In your example, you have commented out the line where you set the value of the Parameter:
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
If you do not set a value for a parameter, it is ignored (and won't exist).
Change to this:
command.Parameters.AddWithValue(name, word);
For clarity, consider this quote:
The value to be added. Use DBNull.Value instead of null, to indicate a null value.
From here: SqlParameterCollection.AddWithValue Method

On var name = "#word" + (i++).ToString(); use just i, increment somewhere else.

Related

How to delete multiple rows in C# using a SQL query?

I have code for deleting a row in C# using a SqlCommand. But I want to delete multiple rows. Can anyone help me with this? I am new to C#.
This is my code - please help. Thank you in advance.
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
You can build a comma separated userid list like -
string strUserIds = string.Empty();
for(int i=0; i<dataGrid.Count;i++)
{
strUserIds = strUserIds +","+ dataGrid.SelectedRows[0].Cells[0].Value;
}
--Remove last unwanted comma from strUserIds
then execute sql query as "DELETE FROM EmployeeTbl WHERE UserID in (" + strUserIds + ")"
This will delete multiple records from table.
Just Make some changes in Your Coding !
Delete All Selected Rows
Run Your select * from ActiveUser
public void deldata()
{
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
}
public void showdata()
{
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
You can use something like this; i didn't test the code but it should work if you create the parameters you need, before running code you have to create a type table, please see the link for details.
using (connection)
{
string sql ="Delete from YourTable t join #yourTypeTable i on t.id = i.Id:";
SqlCommand deleteCommand = new SqlCommand(sql, connection);
SqlParameter tvpParam = deleteCommand.Parameters.AddWithValue("#yourTypeTable", yourIdList);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.yourTypeTable";
deleteCommand.ExecuteNonQuery();
}

Reading sql one row at a time c#

public void addintovisitor()
{
string companyname = (txtvisitor.Text.ToUpper());
DataSet result = new DataSet();
visitorcompany vc = new visitorcompany();
string Location1 = Convert.ToString(Session["location"]);
vc.checksamecompanyname(ref result, Location1);
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
}
else
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
My visitorcompany class:
public int checksamecompanyname(ref DataSet result, string Location1)
{
string strConn = Convert.ToString(
ConfigurationManager.ConnectionStrings
["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand
("select Companyname from tblVisitorcompany where Location1 ='" + Location1 + "'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(result, "details");
conn.Close();
//Return 0 when no error occurs.
return 0;
}
I am trying to search one row at a time to check whether the sql table got the same companyname. if there is already exisiting companyname, the program will do nothing. If this is a new companyname, the program will add companyname into the sql table. However, when adding new companyname, the program will add more than once. Can someone please help me to re-edit my program such that it only add one new companyname. Many thanks.
using( var connection = new SqlConnection( "my connection string" ) ) {
using( var command = connection.CreateCommand() ) {
command.CommandText = "SELECT Column1, Column2, Column3 FROM myTable";
connection.Open();
using( var reader = command.ExecuteReader() ) {
var indexOfColumn1 = reader.GetOrdinal( "Column1" );
var indexOfColumn2 = reader.GetOrdinal( "Column2" );
var indexOfColumn3 = reader.GetOrdinal( "Column3" );
while( reader.Read() ) {
var value1 = reader.GetValue( indexOfColumn1 );
var value2 = reader.GetValue( indexOfColumn2 );
var value3 = reader.GetValue( indexOfColumn3 );
// now, do something what you want
}
}
connection.Close();
}
dont use companyname as an argument of your insert command, since it is stays the same in for loop. Use result.Tables["details"].Rows[i]["Companyname"].ToString() instead:
...
cmd.Parameters.AddWithValue("#Companyname", result.Tables["details"].Rows[i]["Companyname"].ToString());
...
Check if the value exists, then add it if not.
A simple change in your code:
bool valueFound = false;
// check if the value exists
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
// it exists so we exit the loop
valueFound = true;
break;
}
}
// we have looped all the way without finding the value, so we can insert
if(!valueFound)
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Off course you could check if the value exists in a more efficient way, but this should at least solve your specific problem.

How to show SQL query result in a Textbox?

I have the following code:
dbConnection cn = new dbConnection();
SqlCommand cmd = new SqlCommand();
protected void dropdown_student_SelectedIndexChanged(object sender, EventArgs e)
{
string StudentGUID = dropdown_student.SelectedValue;
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = " + StudentGUID + " ";
dr = cn.cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
textbox_total.Text = dr["Total"].ToString();
}
cn.con.Close();
}
}
I want to show the total marks value in the textbox but it does not work. Can anyone point me in the right direction?
Try something like this:
// define your query upfront - using a PARAMETER!
string query = "SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = #StudentID;";
// put the SqlConnection and SqlCommand into using blocks
using (dbConnection cn = new dbConnection())
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define the parameter value
cmd.Parameters.Add("#StudentID", SqlDbType.UniqueIdentifier).Value = dropdown_student.SelectedValue;
cn.Open();
// use ExecuteScalar if you fetch one row, one column exactly
object result = cmd.ExecuteScalar();
cn.Close();
if(result != null)
{
int value = (int)result;
textbox_total.Text = value.ToString();
}
}
You SQL query is wrong. Try like below:
string query = string.Format("SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = '{0}';", StudentID);
Always try to follow this kind of standard practice and you will never fail.
Try putting single Quote around the GUID variable in SQL query.
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = '" + StudentGUID + " '";

SqlDataAdapter is giving me 0 results

SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd = CreateParameterizedQuery();
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
DataTable tbl = new DataTable();
dap.Fill(tbl);
if (tbl.Rows.Count > 0)
{
grid.DataSource = tbl;
}
The actual SQL Query will produce results in SQL Management Studio. However I am getting 0 Rows of Data. I set a breakpoint at tbl.Rows.Count and I see it's 0 and stepping will skip the necessary code to set the DataSource.
private SqlCommand CreateParameterizedQuery()
{
SqlCommand command = new SqlCommand();
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [databaseName].[dbo].[customerTable].[name], [databaseName].[dbo].[customerTable].[dos], [databaseName].[dbo].[customerTable].[ACC], [databaseName].[dbo].[reportTable].[id], [databaseName].[dbo].[reportTable].[ACC], [databaseName].[dbo].[reportTable].[fullreport] FROM [databaseName].[dbo].[reportTable], [databaseName].[dbo].[customerTable] WHERE ";
int i = 0;
foreach (string word in allTheseWords)
{
var name = "#word" + (i++).ToString();
command.Parameters.AddWithValue(name, "'%" + word + "%'");
SQLQuery = SQLQuery + String.Format(" [databaseName].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
}
SQLQuery = SQLQuery + " [databaseName].[dbo].[customerTable].[ACC] = [databaseName].[dbo].[reportTable].[ACC]";
command.CommandText = SQLQuery;
}
return command;
}
I am using WinForm with C# on Windows 8.
The SQLQuery variable contains this data when debugging
SELECT distinct [databaseName].[dbo].[customerTable].[name], [databaseName].[dbo].[customerTable].[dos], [databaseName].[dbo].[customerTable].[ACC], [databaseName].[dbo].[reportTable].[customerID], [databaseName].[dbo].[reportTable].[ACC], [databaseName].[dbo].[reportTable].[fullreport] FROM [databaseName].[dbo].[reportTable], [databaseName].[dbo].[customerTable] WHERE [databaseName].[dbo].[reportTable].[fullreport] LIKE #word0 AND [databaseName].[dbo].[customerTable].[ACC] = [databaseName].[dbo].[reportTable].[ACC]
debugMySQL is a method that spits out the SQL Query with the parameters substituted
public void debugMySQL()
{
string query = command.CommandText;
foreach (SqlParameter p in command.Parameters)
{
query = query.Replace(p.ParameterName, p.Value.ToString());
}
textBox1.Text = query;
}
The output looks like
SELECT distinct [databaseName].[dbo].[customerTable].[name], [databaseName].[dbo].[customerTable].[dos], [databaseName].[dbo].[customerTable].[ACC], [databaseName].[dbo].[reportTable].[id], [databaseName].[dbo].[reportTable].[ACC], [databaseName].[dbo].[reportTable].[fullreport] FROM [databaseName].[dbo].[reportTable], [databaseName].[dbo].[customerTable] WHERE [databaseName].[dbo].[reportTable].[fullreport] LIKE '%single%' AND [databaseName].[dbo].[customerTable].[ACC] = [databaseName].[dbo].[reportTable].[ACC]
You can see parametrized query with its argument value using SQL Profiler.

How to ignore all other database parameters when retrieving one database parameter

I created a simple code that retrieves a database parameter which is ("SOPNUMBE", ordernumber)
However, sometimes an employee will fill out an incorrect order giving me a "LIFTxxxx" value instead of a SOPNUMBE which is "ORDxxxxx" etc. Since L is before S, my ftp site processes LIFT first creating an error. I would really like to have this application ignore everything besides "SOPNUMBE", I feel this is a pretty simple question and to me it sounds like a simple if then statement. But I am having trouble wording it. Any help would be greatly appreciated!!
public bool UpdateOrderToShipped(string order)
{
orderNumber = order;
string batch = ConfigurationManager.AppSettings["SuccessfulOrderBatch"];
string statement = "UPDATE SOP10100 SET BACHNUMB = '"+ batch +"' WHERE SOPNUMBE = #SOPNUMBE";
SqlCommand comm = new SqlCommand(statement, connectionPCI);
comm.Parameters.Add("SOPNUMBE", orderNumber);
try
{
comm.Connection.Open();
comm.ExecuteNonQuery();
comm.Connection.Close();
}
catch(Exception e)
{
comm.Connection.Close();
KaplanFTP.errorMsg = "Database error: " + e.Message;
}
statement = "SELECT SOPTYPE FROM SOP10100 WHERE SOPNUMBE = #SOPNUMBE";
comm.CommandText = statement;
SqlDataAdapter da = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
da.Fill(dt);
soptype = dt.Rows[0]["SOPTYPE"].ToString();
return true;
}
LAs noted in my comment, if you aren't comfortable changing this code with an if statement, then you probably shouldn't be maintaining this code. (Do you know where else this code is referenced? Your change will be affecting those places.)
But here you go...
public bool UpdateOrderToShipped(string order)
{
if ((String.CompareOrdinal(order, 0, "ORD", 0, 3) == 0)
{
orderNumber = order;
string batch = ConfigurationManager.AppSettings["SuccessfulOrderBatch"];
string statement = "UPDATE SOP10100 SET BACHNUMB = '"+ batch +"' WHERE SOPNUMBE = #SOPNUMBE";
SqlCommand comm = new SqlCommand(statement, connectionPCI);
comm.Parameters.Add("SOPNUMBE", orderNumber);
try
{
comm.Connection.Open();
comm.ExecuteNonQuery();
comm.Connection.Close();
}
catch(Exception e)
{
comm.Connection.Close();
KaplanFTP.errorMsg = "Database error: " + e.Message;
}
statement = "SELECT SOPTYPE FROM SOP10100 WHERE SOPNUMBE = #SOPNUMBE";
comm.CommandText = statement;
SqlDataAdapter da = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
da.Fill(dt);
soptype = dt.Rows[0]["SOPTYPE"].ToString();
return true;
} else
{
return false;
}
}

Categories