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();
}
}
Related
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();
}
}
I want to display my oracle sql table on datagridview using windows form on visual studio 2017 c#. I am using oracle.data.access.client and type
private void button1_Click(object sender, EventArgs e)
{
string oradb = "Data Source=127.0.0.1;User Id=practice;Password=practice;";
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from test_dummy";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
dataGridView1.DataSource = dr;
conn.Dispose();
}
I don't get it.. How do i make this work? . >.<
DataSource of DataGridView in this case should be DataTable not DataReader so I think you should change your code like this
OracleDataReader dr = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(dr);
dataGridView1.DataSource = dataTable;
If you change like this and debug it has data but still nothing to display, you should check your data column binding
I have this code:
private void FirmaEkleB_Click(object sender, EventArgs e)
{
string query = "INSERT INTO FIRMATABLE VALUES (#CompanyName)";
SqlConnection sqlconnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, sqlconnection);
Form1 LoginForm = new Form1();
sqlconnection.Open();
command.Parameters.AddWithValue("#CompanyName", FirmaIsmiTextbox.Text);
command.ExecuteScalar();
SqlCommand com2 = new SqlCommand("Select FirmaIsmi FROM FIRMATABLE WHERE ID = 9", sqlconnection);
MessageBox.Show(com2.ExecuteScalar().ToString());
LoginForm.fillFirmaList();
}
fillFirmaList() looks like this:
public void fillFirmaList()
{
connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("SELECT * FROM FirmaTable", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable firmaTable = new DataTable();
adapter.Fill(firmaTable);
FirmaCombo.DataSource = firmaTable;
FirmaCombo.DisplayMember = "FirmaIsmi";
FirmaCombo.ValueMember = "Id";
}
I don't know what I'm doing wrong but I can't seem get my combobox to update from the table I have. The manually added rows show up but not the one that I add
Keep in mind that I'm just starting out in SQL Server and database stuff.
If more info is needed tell me.
Change your Insert query to
INSERT INTO FIRMATABLE (FirmaIsmi) VALUES (#CompanyName)
You need to include all your column names for which you are adding the VALUES.
And
change ExecuteScalar to command.ExecuteNonQuery().
Add try-catch block and see what exception does it throws after ExecuteNonQuery
I have a dropdownlist that is populated with semesters. When the semester selection is changed, I want to populate another dropdownlist with courses available for that semester based on the semesterID. I have a stored procedure in SQL Server that gets courses based on the semesterId parameter. The semester list is populated just fine, but when I select a semester, I get an error while using the SP to get the courses. The error says Procedure or function 'GetCourses' expects parameter '#semesterId', which was not supplied. even though I supply the value for #semesterId before I open the connection. What am I doing wrong?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
PopulateSemesterList();
}
private void PopulateSemesterList()
{
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.GetSemesters", conn);
conn.Open();
DDSemesters.DataSource = cmd.ExecuteReader();
DDSemesters.DataTextField = "semesterName";
DDSemesters.DataValueField = "semesterId";
this.DataBind();
conn.Close();
conn.Dispose();
DDSemesters.Items.Insert(0, new ListItem("Select Semester", "0"));
DDSemesters.SelectedIndex = 0;
}
protected void DDSemesters_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList DDSemesters = sender as DropDownList;
int selectedSemester = Convert.ToInt32(DDSemesters.SelectedItem.Value);
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.GetCourses", conn);
cmd.Parameters.Add(new SqlParameter("#semesterId", selectedSemester));
conn.Open();
DDCourses.DataSource = cmd.ExecuteReader();
DDCourses.DataTextField = "courseName";
DDCourses.DataValueField = "courseId";
this.DataBind();
conn.Close();
conn.Dispose();
DDCourses.Items.Insert(0, new ListItem("Select Course", "0"));
DDCourses.SelectedIndex = 0;
DDCourses.Visible = true;
CoursesLbl.Visible = true;
}
As far as I can tell your CommandType is the default, Text, which causes the CommandText to be interpreted as an SQL query instead of just a stored procedure name.
You'll want to set it to StoredProcedure instead:
cmd.CommandType = CommandType.StoredProcedure;
Alternatively you could make your command a full SQL query that properly passes the parameters to the stored procedure.
I am trying to populate a DataGridView based on a comboBox selection. I don't know where I am going wrong - please help..
Here is my code:
public void GetTestGroups()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter da = new SqlDataAdapter("select LabTestGroupId,GroupName from tbl_LabTestGroup", con);
DataTable dt = new DataTable();
da.Fill(dt);
cbTestGroup.DataSource = dt;
cbTestGroup.DisplayMember = "GroupName";
cbTestGroup.ValueMember = "LabTestGroupId";
}
}
private void cbTestGroup_SelectedIndexChanged(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter da = new SqlDataAdapter("spGetTestNames", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("#LabTestGroupId", cbTestGroup.SelectedValue.ToString());
DataTable dt = new DataTable();
da.Fill(dt);// Error in this line.
dgvLabTests.DataSource = dt;
}
}
My stored procedure:
create procedure spGetTestNames
#LabTestGroupId int
as
begin
select TestNames
from tbl_LabTests
where LabTestGroupId = #LabTestGroupId
end
You're passing a string to your stored procedure when it's expecting an int. Change the code that sets the #LabTestGroupId parameter like this.
da.SelectCommand.Parameters.AddWithValue(
"#LabTestGroupId",
int.Parse(cbTestGroup.SelectedValue.Item["LabTestGroupId"].ToString()));
Or you need to determine how to convert the SelectedValue into the desired int value. I suggest debugging and viewing the SelectedValue in the watch window to determine exactly what it is and how to get to the desired value.