Unable to fill data grid view dynamically using stored procedure - c#

I'm writing a program using C# win forms and SQL Server 2012. In one of my forms I have a combobox a button and a datagrid view. I want the data grid view to be filled every time I change the value in combo box.
This code doesn't work :( (it does not return an error)
private void button1_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(comboBox2.SelectedValue.ToString());
//int idc = 100;
DataSet ptDataset = new DataSet();
string con = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spDispProductInfo", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#id", id);
sqlCmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
da.Fill(ptDataset);
dataGridView2.DataSource = ptDataset;
sqlCon.Close();
}

Try this.
int id = Convert.ToInt32(comboBox2.SelectedValue.ToString());
//int idc = 100;
DataSet ptDataset = new DataSet();
string con = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spDispProductInfo", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#id", id);
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
da.Fill(ptDataset);
dataGridView2.DataSource = ptDataset.Tables[0];
sqlCon.Close();

You must Use the Event of your comboBox clik not the button.
Just try to add this button1_click event to the combobox that you have.

Set your Code in SelectedIndexChanged event Of your comboBox
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ptDataset = new DataSet();
string con = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spDispProductInfo", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#id", Convert.ToInt32(comboBox2.SelectedValue.ToString()));
sqlCmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
da.Fill(ptDataset);
dataGridView2.DataSource = ptDataset;
sqlCon.Close();
}

Related

ExecuteNonQuery: Connection property has not been initialized. c sharo

may be i am tired but any body can say what is the poblem?
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='c:\users\deltagare\documents\visual studio 2015\Projects\School\School\school.mdf';Integrated Security=True");
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'schoolDataSet.student' table. You can move, or remove it, as needed.
//this.studentTableAdapter.Fill(this.schoolDataSet.student);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from student";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
student = new StudentController();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
studentGridView.DataSource = dt;
conn.Close();
}
You have either to use the SqlCommand(string,SqlConnection) overload, or set the SqlCommand.Connection property:
SqlCommand cmd = new SqlCommand("select * from student",conn);
Or
cmd.Connection=conn;
you have to assign the connection to the command before you execute it:
cmd.Connection = conn

fill grid view in c#

I am new in using visual studio and ADO.NET. I want to display result from sqlserver database in data gridview.
This is my code but it does not fill data to gridview.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand Cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(Cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
SqlDataReader reader = Cmd.ExecuteReader();
dt.Load(reader);
dataGridView1.DataSource = dt;
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
Why are you binding to grid two times?
If your application is ASP.NET Webforms and you are trying to bind the GridView(ID for the GridView is "dataGridView1"), then make your binding to single time and to bind data for GridView you need to use dataGridView1.DataBind(); after dataGridView1.DataSource = dt;
If your application is WindowsForms application then modify your code like below
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
string connectionString = "Define your connection string here";
using(SqlConnection con = new SqlConnection(connectionString ))
{
SqlCommand cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
}

Use SQL queries virtual console to do any thing on a SQL Server database

How can I use a rich textbox and some pre-connected string to execute direct Transact-SQL queries and get results into a datagridview?
My GUI form is like this:
I want to use any SQL queries in this rich textbox and get result in data grid view
I using this code for query and fill data gridview
SqlConnection c = new SqlConnection(#"Data Source=.;Initial Catalog=db3;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter a = new SqlDataAdapter("select * from phone", c);
DataTable t = new DataTable();
a.Fill(t);
dataGridView1.DataSource = t;
}
So how do I modify it to this?
SqlConnection c = new SqlConnection(#"Data Source=.;Initial Catalog=db3;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter a = new SqlDataAdapter(Textbox1.Text, c);
DataTable t = new DataTable();
a.Fill(t);
dataGridView1.DataSource = t;
}
I also used Pravin Deshmukh code in another button and get error:
Update 3: used suggested code and got a reference error
private void button3_Click(object sender, EventArgs e)
{
string SqlString = textBox2.Text; // here you can have your user query from textbox
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.;Initial Catalog=db3;Integrated Security=True"].ConnectionString.ToString());
conn.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(SqlString, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
cmd.Dispose();
}
Error:
Try this
string SqlString= "your sql query";
SqlConnection conn = new SqlConnection(#"Data Source=.;Initial Catalog=db3;Integrated Security=True");
conn.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(SqlString, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
cmd.Dispose();
Set datagridview generate columns automatic
EDIT : or
string SqlString= textbox1.Text; // here you can have your user query from textbox

cascading comboBox in windows form using c#

I am trying to Fill Combobox2 on combobox1 selectedText changed from the same table in windows form application. I am using sql serevr 2008 database. I am unable to fill combobox2 on combobox selected text changed.
Here is what i have tried:
private void Purchase_Load(object sender, EventArgs e)
{
fillName();
comboBoxName.SelectedIndex = -1;
}
private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxName.SelectedText != "")
{
fillMake();
}
}
private void fillName()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Name from Item";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Make";
}
private void fillMake()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Make from Item Where Item_Name='" + comboBoxName.SelectedText + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Make";
comboBoxName.ValueMember = "Item_Name";
comboBoxName.SelectedIndex = -1;
comboBoxName.Text = "Select";
}
Sql server table for Items
Item_Code Item_Name Item_Make Item_Price UnitofMeasurement
Cable anchor 45.0000 meter
Cable polycab 30.0000 meter
Button anchor 15.0000 unit
Button havells 20.0000 unit
Switch cona 70.0000 unit
I have searched for solution but was unfortunate.
please help me out.
Thanks in advance.
It's a little difficult to figure out what you're trying to do, but it sounds like you are trying to populate a second combo box (comboBoxMake?) depending on what is selected in comboBoxName. I am basing this answer on that assumption. Apologies if I have this wrong.
There are lot of things that need attention in this code. Let's look at fillName() first.
private void fillName()
{
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
con.Open();
string str = "Select Item_Name from Item";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
cmd.ExecuteNonQuery();
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Make";
}
You need to Dispose() your database objects. This can be accomplished pretty cleanly with using { .. } blocks.
You don't need to manually open the connection; filling the table with the data adapter
does this automatically.
You don't need the call to ExecuteNonQuery().
You should use the SqlDataAdapter constructor overload that takes a command object, since you have already manually created the command.
Finally, based on my assumption of your goal I have added a distinct to your query so it only gets the unique Item_Names.
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
On to fillMake(). The same suggestions apply that I noted above. Additionally:
Parameterize your SQL. Parameterize your SQL. Not only is this far, far safer than concatenating your SQL together, it is much cleaner. Seriously, read about SQL injection: http://en.wikipedia.org/wiki/SQL_injection
The fillMake() method in your original post seems to be repopulating comboBoxName. Is this correct? You mention two combo boxes but your code only references one. I am assuming you mean to populate another combo box (comboBoxMake?) here:
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name = #item_name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#item_name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.DisplayMember = "Item_Make";
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.SelectedIndex = -1;
comboBoxMake.Text = "Select";
}
}
}
}
Lastly, change the code in the event handler so it looks at the Text rather than the SelectedText property:
private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text)) // Text instead of SelectedText
{
fillMake();
}
}

A form is loaded but how to extract data from SQL to combobox?

Still learning C#
A comboBox is created and Tables called mainCat and subCat is created.
I have a code , but i am stuck to understand on how to get the data from mainCat to the comboBox , which is then used by another comboBox for the subCat to set a subcategory.
The Get Connection is underlined red. Why?
Here is my code -
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category ,Category.Id from Category", Con);
SqlCommand cmd = new SqlCommand("SELECT * from MAINCAT");
DataTable dt = new DataTable();
da.Fill(dt);
mainCatU.DataSource = dt;
mainCatU.DisplayMember = "Category";
mainCatU.ValueMember = "Id";
mainCatU.Text = "<-Please select Category->";
myComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
}
}
So i then i tried another code.. but still doesnt work..
public partial class User : Form
{
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Integrated Security=True";
con.Open();
MessageBox.Show("Database connected");
ds1 = new DataSet();
string sql = "SELECT * from MAINCAT";
da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con);
da.Fill(ds1, "SCSID");
mainCatU.DataSource = ds1;
con.Close();
mainCatU.Text = "<-Please select Category->";
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
}
}
then i just used the data bound item function through the combobox GUI..
this.mAINCATTableAdapter.Fill(this.masterDataSet.MAINCAT);
but , the box didn't show any value , except "System.Data.DataRowView" in the comboBox
==================================================================================
System.Data.SqlServerCe.SqlCeConnection con; //not used at the moment
System.Data.SqlServerCe.SqlCeDataAdapter da; //not used at the moment
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
MessageBox.Show("Database connected");
SqlDataAdapter da = new SqlDataAdapter("SELECT * from MAINCAT", conn);
ds1 = new DataSet();
da.Fill(ds1, "MainCat");
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
}
===============
and the combo box is still not showing anything from the database table
You need to create the function GetConnection():
public string ConnectionString { get; set;}
public SqlConnection GetConnection()
{
SqlConnection cn = new SqlConnection(ConnectionString);
return cn;
}
TBH, unless you want to do something in GetConnection, you might be better just creating it inline:
using (SqlConnection Con = new SqlConnection(ConnectionString))
{
EDIT:
Based on your revised question, I think the problem now may be here:
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
My guess is that your table structure is not maincat.maincat. The display and value members should be set to the field name that you wish to display.
I am really sorry I am a vb developer but the concept is same to populate data into combo using sql is
Declare SQLConnection Declare SQLDataReader Declare SQLCommand
Try
If Con.State = ConnectionState.Closed Then
Con.Open()
cmd.Connection = Con
cmd.CommandText = "Select field1, field2 from table"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBoxName.Items.Add(dr.GetString(0))
ComboBoxName.Items.Add(dr.GetString(1))
Loop
Con.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Hope it works for you.

Categories