I am trying to display the data in a datagridview in my c# windows forms project. I keep getting this error
"Fill: SelectCommand.Connection property has not been initialized"
is there anything i'm doing wrong here:
private void Form1_Load(object sender, EventArgs e)
{
try
{
SqlCommand db = new SqlCommand("select * from Tbls");
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = db;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have to assign an SqlConnection object to your SqlCommand object.
db.Connection = conn;
Where conn is your SqlConnection object.
Initialize your SqlConnection object like so:
var conn = new SqlConnection(/*Connection String*/);
You create a new command:
SqlCommand db = new SqlCommand("select * from Tbls");
But, what SqlConnection are you using? You're not. You need to create a command with a connection. Generally you do this FROM a SqlConnection See: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.createcommand(v=vs.110).aspx
Related
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
I wish to load the datatable from database to data grid view,but I get the error saying "The operation & method is not implemented". I do review the video over here: http://www.youtube.com/watch?v=Sm5mxkytfWk; This is my very first time to do this, hope to get to solve it.
Below is my code:
private void button1_Click(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\oo\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("SELECT* from Data.itemInfo;", conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MySqlCommand cmdDataBase = new MySqlCommand("SELECT* from Data.itemInfo;", conDataBase);
yours Sql query contain extra semicolen
from
SELECT* from Data.itemInfo;
to
SELECT* from Data.itemInfo
How to: Bind Data to the Windows Forms DataGridView Control
private void toolStripButton1_Click(object sender, EventArgs e)
{
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Dsn=mdc;" +
"Uid=root;" +
"Pwd=;";
OdbcCommand cmd = new OdbcCommand("select * from tbl_delivery");
cmd.CommandType = CommandType.Text;
DataSet dt = new DataSet();
OdbcDataAdapter ds = new OdbcDataAdapter();
ds.Fill(dt);
tbl_deliveryDataGridView.DataSource = dt;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
there is always an error everytime i am going to run the program, i don't know where is the error. i tried editing the code yet still the error keeps on popping out.
You getting error because you haven't assign OdbcCommand to OdbcDataAdapter and trying to execute Fill method. you should assign OdbcCommand to OdbcDataAdapter like this
OdbcDataAdapter ds = new OdbcDataAdapter(cmd,conn);
And then try to Fill DataTable
conn.Open();
DataSet dt = new DataSet();
OdbcDataAdapter ds = new OdbcDataAdapter();
ds.Fill(dt);
tbl_deliveryDataGridView.DataSource = dt;
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();
}
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.