using (SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-IIDC3HF\SQLEXPRESS;Initial Catalog=EmployeeNotifier;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Name,Salary FROM YOUR TABLE", con);
SqlDataReader dr = cmd.ExecuteReader();
dataGridView1.DataSource = dr;
dataGridView1.DataBind(); // causing problem here
con.Close();
}
I tried this code but this displays an error
Does Not Contain Definition for DataBind
var select =q;
var c = new SqlConnection(#"Your Connection String here ");
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
Now i try this Code and its works really fine for me
Problem is that the datareader must iterate over the an object
try this instead create a custome class to hold your data.like below.
If that is too much trouble use an data adaptor and use DataSets
List<myCustomerCLass> list = new List<myCustomerCLass>();
con.Open();
SqlCommand cmd = new SqlCommand("Select Name,Salary FROM YOUR TABLE", con);
SqlDataReader dr = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
myCustomerCLass test = new myCustomerCLass();
test.property1 = reader["Property1"]
test.property2 = reader["Property2"]
test.property3 = reader["Property3"]
list.add(test);
}
}
reader.Close();
dataGridView1.DataSource = list;
dataGridView1.DataBind(); // causing problem here
con.Close();
Related
I'm passing a query and parameter from a WinForm to a database class. The
The code on the Form looks like this:
string selectedComp = "CPSI";
string catsQuery = "SELECT id, category, old_value, old_desc, new_value, new_desc, reference1, reference2 FROM masterfiles.xref WHERE company_name = '#company' ORDER BY category, old_value";
Db categoriesData = new Db();
dgvCategories.DataSource = categoriesData.GetData(catsQuery, selectedComp);
And in my database class my code to populate the datatable/set is this:
public DataTable GetData(string selectQuery, string selectedComp)
{
NpgsqlConnection conn = new NpgsqlConnection(connString);
DataSet ds = new DataSet();
NpgsqlCommand cmd = new NpgsqlCommand(selectQuery, conn);
cmd.Parameters.Add(new NpgsqlParameter("#company", selectedComp));
//cmd.Parameters.AddWithValue("#company", selectedComp);
//cmd.Parameters.Add("#company", NpgsqlDbType.Text);
//cmd.Parameters["#company"].Value = selectedComp;
try
{
conn.Open();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);
conn.Close();
da.Fill(ds);
return ds.Tables[0];
}
}
But putting a breakpoint at NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);, selecctQuery hasn't changed - the '#company' is still in the query.
What am I missing?
The root problem is that you're passing the query to the data adapter instead of the command. Change
NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);
to
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
I would also use using to dispose of all objects, and don't close the connection until the dataset is filled:
using(NpgsqlConnection conn = new NpgsqlConnection(connString))
using(NpgsqlCommand cmd = new NpgsqlCommand(selectQuery, conn))
{
cmd.Parameters.Add(new NpgsqlParameter("company", selectedComp));
conn.Open();
using(NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
}
conn.Close();
return ds.Tables[0];
}
I have datagridview, that i must fill by 5 tables. I declared SqlCommand and SqlConnection.
After that I use somethine like this:
selCommand.Connection = conn;
dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = selCommand;
ad.Fill(dt);
dataGridView1.DataSource = dt;
As a result I have column headers of my query in datagridview, but don't have data.
I tried use this code:
selCommand.Connection = conn;
dt = new DataTable();
SqlDataReader dr = selCommand.ExecuteReader();
dt.Load(dr);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
dr.Close();
It was working, but I something change and I can't understand why it does not work.
Try this:
DataTable table = null;
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
try
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM Something WHERE Id = #Id";
cmd.Parameters.Add(new SqlParameter("#Id", YourValue));
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
table = new DataTable();
adapter.Fill(table);
}
}
catch (Exception ex)
{
//Handle your exception;
}
}
dataGridView1.DataSource = table;
How can i get the value of company_name from Comp table and store it on a comboBox?
here is my initial code on getting the values from Database and store it on a combobox:
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
it point out to da.fill(ds) and says "Could not locate entry in sysdatabases for database 'select company_name from JO'. No entry found with that name. Make sure that the name is entered correctly."
hope for your reply thanks!
Use datareader it is much simpler \
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(Sql, conn);
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
combobox1.Items.Add(DR[0]);
}
If you set up your connection string to be something of this sort:
string SqlConnectionString = "Data Source=[SERVER];Initial Catalog=[DATABASE];"
Then using that set up, you can set your string 'Sql' as:
string Sql = "select company_name from dbo.Comp";
This could be a possible set up you could use to read out the values.
using (SqlConnection saConn = new SqlConnection(this.ConnectionString))
{
saConn.Open();
string query = "select DBName from dbo.Company";
SqlCommand cmd = new SqlCommand(query, saConn);
using (SqlDataReader saReader = cmd.ExecuteReader())
{
while (saReader.Read())
{
string name = saReader.GetString(0);
combobox1.Add(name);
}
}
saConn.Close();
}
I would like to introduce you a very simple way to SQL data into a combobox as:
first you have a create a SQL table,
in C# platform drop a combobox and go to its property,
in the property menu click on "DataSource"
specify the database and table to load into combobox,
Note, the combobox name and table's row should be the same.
{
SqlConnection con =new SqlConnection("Data Source=Server_Name;Initial Catalog=Database_Name;integrated security=true");
SqlCommand cmd;
SqlDataReader dr;
private void CashMemoForm_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("Select Column_Name From Table_Name", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr[0]).ToString();
}
}
}
Have you ever tried Entity Framework for database access and dto creation?
Change your line to cmd.CommandType = CommandType.Text; instead of cmd.CommandType = CommandType.StoredProcedure;
Try this
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("--Select--", "0"));
}
There is no use of for loop. you just need to check that whether the dataset contains rows or not.
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("Select", "0"));
}
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
public System.Data.DataTable EmployeeViewAll()
{
DataTable dtbl = new DataTable();
try
{
// Here it shuld be your database Connection String
string connectionString = "Server = .; database = HKS; Integrated Security = true";
using (SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection(connectionString))
{
SqlDataAdapter SqlDa = new SqlDataAdapter("employeeViewAll", sqlCon);
SqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlDa.Fill(dtbl);
}
return dtbl;
}
catch (Exception)
{
throw;
}
}
public void ComboFill()
{
DataTable dt = new DataTable();
eSP SP = new eSP();
d = SP.EmployeeViewAll();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "department";
comboBox1.ValueMember = "empName";
}
So i currently have two combo boxes. One Being Manufacture the other being model. My sql query looks like this "Select Distinct Model From sheet1 where (Manufacture =#Manufacture)" this works when i execute it and if i were to fill a datagridtable. But if i try to place this into a combobox i get System.data.d...... etc for my selections. How can i just have it show the values instead of all this. What am i doing wrong?
private void ManuComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string manu = comboBox3.Text;
string conStr = "Data Source=CA-INVDEV\\RISEDB01;Initial Catalog=RISEDB01; Integrated Security=True";
string sqlcmd = "SELECT DISTINCT Model FROM Sheet1 WHERE (Manufacture =#Manufacture)";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Close();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource3.DataSource = table;
ModelComboBox.DataSource = bindingSource3;
}
}
}
Can you give this a try?
using (SqlConnection conn = new SqlConnection(conStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
IList<string> modelList = new List<string>()
while (dr.Read())
{
modelList.add(dr[0].ToString());
}
ModelComboBox.DataSource = modelList;
}
If you have set the display member like:
ModelComboBox.DataSource = bindingSource3;
ModelComboBox.DisplayMember = "ColumnName";
And it still shows funny values, what are the values that it shows exactly?
Note, in a toolstrip it looks like you may have to also do:
ModelComboBox.BindingContext = this.BindingContext;
here is a reference
Try adding
ComboBox1.ItemsSource = bindingSource3
if this is your answer then mark it as answer
I am creating a inventory app using c# that pulls its info from sql server. I am making it a tabbed view, with each tab representing a different type of item. I have included some of my code, what I am trying to figure is, is there a better way to do this? I dont feel like the way I am doing is right, even though it works. All my queries for each tab are stored procedures. Secondly, How would I insert and update the database through the grid?
public partial class InventoryWindow : Window
{
private InventoryDS InvDS;
private String connString = "server=PC-server;database=Inventory;user=user;password=password";
String sqlString_Routers = InventoryOutputQuery.InventorySummary_Routers();
public InventoryWindow()
{
InitializeComponent();
if (dgDataView != null)
{
SqlConnection con = new SqlConnection(connString);
SqlDataAdapter adpt = new SqlDataAdapter(sqlString_Routers, con);
DataSet ds = new DataSet();
adpt.Fill(ds, sqlString_Routers);
dgDataView.DataContext = ds;
}
}
private void showTaps()
{
String sqlString_Taps = InventoryOutputQuery.InventorySummary_Routers();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand(sqlString_Routers, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
private void showPower()
{
String sqlString_Power = InventoryOutputQuery.InventorySummary_Power();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand(sqlString_Power, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
private void showSwitches()
{
String sqlString_Switches = InventoryOutputQuery.InventorySummary_Switches();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand(sqlString_Switches, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
And below is how i bind it to the grid:
public void BindGrid(string view)
{
switch (view.ToUpper())
{
case "Routers":
showTaps();
break;
case "POWER":
showPower();
break;
case "SWITCHES":
showSwitches();
break;
case "HUBS":
showHubs();
private void tcDataView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TabItem ti = tcDataView.SelectedItem as TabItem;
if (ti != null)
BindGrid(ti.Header.ToString());
}
break;
My suggestion is to be careful with how we handle SqlConnection. It is a scarce resource and it will run out pretty soon if we are not careful.
Please wrap sql code in a using block, for example:
using (SqlConnection con = new SqlConnection(connString))
{
SqlDataAdapter adpt = new SqlDataAdapter(sqlString_Routers, con);
DataSet ds = new DataSet();
adpt.Fill(ds, sqlString_Routers);
dgDataView.DataContext = ds;
}
The following link will explain the effect of 'using' block in a bit more details.
http://www.codeproject.com/KB/cs/tinguusingstatement.aspx