So I am using MS visual studio to create an application in c# that will pull information from a sql server database.
I have created a textbox and a button to search my gridview. I am using a stored procedure that searched multiple rows to pull information from my Sql Database.
I am having trouble with my aspx.cs code. I have tried so many different ways to create a searchbox but haven't had any luck yet
Here is my code for my search button.
I am getting the error-
"Input string was not in a correct format."
this error is on the line cmd.ExecuteNonQuery();
Help is much appreciated, thank you.
protected void Button_srch_invest1_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionStr))
{
string find = "sp_SrcProtocols";
SqlCommand cmd = new SqlCommand(find, con);
cmd.Parameters.Add("#ORAID", SqlDbType.Int).Value = TextBox_Srch.Text;
cmd.Parameters.Add("#InvestLastName", SqlDbType.NVarChar).Value = TextBox_Srch.Text;
cmd.Parameters.Add("#ManagerLastName", SqlDbType.NVarChar).Value = TextBox_Srch.Text;
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "ORAID");
da.Fill(ds, "InvestLastName");
da.Fill(ds, "ManagerLastName");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
}
By default, a SqlCommand expects a query, not a stored procedure's name. You have to set the command type before executing it.
cmd.CommandType = CommandType.StoredProcedure;
It seems, you are passing same text box value (TextBox_Srch.Text) to all 3 parameters. And first parameter #ORAID is expecting integer value and you might be passing text. So it's causing SQL server to raise below error.
Input string was not in a correct format.
This is what worked (and i changed my sql to just accept one parameter #search)
protected void Button_srch_invest1_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "sp_SrcProtocols";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox_Srch.Text;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
con.Close();
}
}
Related
I have two stored procedures:
spRO_Status_OrderInfo
spRO_Status_Change
Each procedure returns a different table. I have only one user input parameter TN. This parameter I'm reading from search txt line (inputTNReturn.Value)
Each procedure posts data in a different grid view
spRO_Status_OrderInfo -->> gvSearchResults
spRO_Status_Change -->> GridView1
This code returns only LAST stored procedure to last gridView
spRO_Status_Change -->> GridView1
I don't have any idea where is my mistake and why I can get 2 grid view from 2 procedure.
I'll appreciate for any help
protected void btnSearch_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionStr))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "[spRO_Status_OrderInfo]";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spRO_Status_Change";
cmd.CommandType = CommandType.StoredProcedure;
if (inputTNReturn.Value.Trim() != "")
{
SqlParameter param = new SqlParameter("#TN", inputTNReturn.Value);
cmd.Parameters.Add(param);
SqlDataReader rdr = cmd.ExecuteReader();
gvSearchResults.DataSource = rdr;
gvSearchResults.DataBind();
GridView1.DataSource = rdr;
GridView1.DataBind();
lblinputTNReturn.Text = inputTNReturn.Value;
}
}
if (inputTNReturn.Value == "")
{
inputTNReturn.Value = "Please add tracking number";
}
con.Close();
}
}
Here is where you're setting the first stored procedure
cmd.CommandText = "[spRO_Status_OrderInfo]";
cmd.CommandType = CommandType.StoredProcedure;
Here is where you're overwriting the above
cmd.CommandText = "spRO_Status_Change";
cmd.CommandType = CommandType.StoredProcedure;
You're not adding a second command text / type, you're just over writing the first one which is why you're only seeing the second one come out in the output.
I'm importing the table 'tblTable' to Datagridview in C# with:
private void button1_Click(object sender, EventArgs e)
{
con.Open();
//
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM tblTable";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sa = new SqlDataAdapter(cmd);
sa.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
I have written a specific SQLQuery, 'SQLQuery1.sql' that does some groupings from the table 'tblTable' that I'm already importing. What would be the best way to import only the SQLQuyery1.sql in to C#, without importing all the table?
Many thanks
It would probably be best to make your query into a Stored Procedure, and call instead:
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "MyStoredProc";
I am using SQL Server 2014 and Visual Studio 2013. I want to write C# code so that user should check checkbox and select an item from combobox then this item will be sent to a stored procedure in SQL Server. In real I want to send parameter to stored procedure from combobox. Code below written by me but does not work well.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked) ;
SqlConnection con = new SqlConnection(#"Data Source=USER-PC\----);
SqlCommand Cmd = new SqlCommand("select_Info_Person", con);
Cmd.CommandType = CommandType.StoredProcedure;
con.Open();
DataTable dt = new DataTable();
using(SqlDataAdapter da = new SqlDataAdapter(Cmd))
{
da.Fill(dt);
comboBox1.DisplayMember = "Person_Expert";
comboBox1.DataSource = dt;
con.Close();
}
}
No problem, if SP is without any parameter. It seems your connection string is not properly initialized, otherwise no problem at all. Check the Error type and share. Otherwise OK.
It seems that you are not sending any parameter to the Stored procedure
Step 1:
Declare Parameter in your storedprocedure and use it in where condition..
CREATE PROCEDURE select_Info_Person
-- Add the parameters for the stored procedure here
#p1 int = 0
AS
BEGIN
-
-- Insert statements for procedure here
Select * from PersonMaster where personID=#p1
END
GO
Then in the code
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox.Checked) ;
SqlConnection con = new SqlConnection(#"Data Source=USER-PC\----");
SqlCommand Cmd = new SqlCommand("select_Info_Person", con);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("#p1", comboBox1.SelectedValue.ToString());
// or if you dont have value feild
// Cmd.Parameters.AddWithValue("#p1", comboBox1.Selecteditem.Text.ToString());
con.Open();
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(Cmd))
{
da.Fill(dt);
//I cannot understand what you are doing using below
// comboBox1.DisplayMember = "Person_Expert";
// comboBox1.DataSource = dt;
// con.Close();
}
}
In sql I normally execute my procedure using
exec dbo.usp_FCS 'TIMV','serial'
And I tried something somewhat the same in c# but it seems I got this wrong
using (SqlConnection connection = new SqlConnection("Data Source=;Initial Catalog=;User ID=;Password="))
{
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" + "'" + MachineName + " ','serial' " , connection))
{
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
}
catch (SqlException ex)
{
label6.Visible = true;
label6.Text = string.Format("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
}
}
My question is,how can I give those 2 inputs 'TIMV' and 'serial' of my stored procedure using c#?
Edit:
I tried something like this:
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" , connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#p2", SqlDbType.VarChar).Value = "serial";
try
{ my code...
And it is still not working
The most correct way to add a parameter to an SqlCommand is through the Add method that allows you to specify the datatype of the parameter and, in case of strings and decimals, the size and the precision of these values. In that way the Database Engine Optimizer can store your query for reuse and be a lot faster the second time you call it. In your case I would write
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 20).Value = MachineName;
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20).Value = "serial";
This assumes that your stored procedure receives two parameters named EXACTLY #mname and #serial, the type of the parameters is NVarChar and the length expected is 20 char. To give a more precise answer we need to see at least the first lines of the sp.
In your code above also the execution of the command is missing. Just creating the command does nothing until you execute it. Given the presence of an SqlDataAdapter I think you want to fill a DataSet or a DataTable and use this object as DataSource of your grid. Something like this
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
yourDataGrid.DataSource = dt;
And if this is an ASP.NET app, also the DataBind call
yourDataGrid.DataBind();
You use the Parameters collection of the SqlCommand class to send parameters to a stored procedure.
Suppose your parameter names are #p1 and #p2 (Please, for your sake, don't use names like this ever) - your c# code would look like this:
using (var cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya", connection))
{
cmd..CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#21", SqlDbType.VarChar).Value = "serial";
try
{
// rest of your code goes here....
Note: use the SqlDbType value that fits the parameters data type.
Try this:
DataSet ds = new DataSet("dts");
using (SqlConnection conn = new SqlConnection
("Data Source=;Initial Catalog=;User ID=;Password="))
{
try
{
SqlCommand sqlComm = new SqlCommand("usp_FCS_GetUnitInfo_Takaya",conn);
sqlComm.Parameters.AddWithValue("#p1", MachineName);
sqlComm.Parameters.AddWithValue("#p2", "serial");
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
catch (Exception e)
{
label6.Visible = true;
label6.Text = string.Format
("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
The database that I am connecting to has a table with a Full Text Search index. This works correctly.
select * from MyTable where contains(*, 'value')
In WPF if I send that exact command down it works. However value is not hard coded it is something an user types in so it needs to be protected for SQL injection. The issue is that in doing so it does not return results. Here is my code;
DataTable dt = new DataTable();
string ConString = "Data Source=127.0.0.1,1433;Initial Catalog=MyDB;User Id=sa;Password=amazingSecurePassword;";
using (SqlConnection con = new SqlConnection(ConString))
{
string sqlCMD = "select * from MyTable where contains(*, #s1)"
SqlCommand cmd = new SqlCommand(sqlCMD, con);
SqlDataAdapter da = new SqlDataAdapter();
try
{
con.Open();
cmd = new SqlCommand(sqlCMD, con);
cmd.Parameters.Add(new SqlParameter("#s1", "value"));
da.SelectCommand = cmd;
da.Fill(dt);
con.Close();
}
catch (Exception x)
{
//Error logic
}
finally
{
cmd.Dispose();
con.Close();
}
}
Edit: #Mike comment worked. Change the SqlDbType.NVarChar fixed the issue
As noted in the above comment, setting the SQlDbType to NVarChar during the creation of the SqlParameter helps the CLR determine the right data type. More info about the SqlParameter constructor at MSDN.