I am developing a relatively simple code that allows you to make a select to my database to extract the values of two columns wanted to be both of X.
My problem using the DataBindTable method is not allowing me to define the second X.
Here is the code for the first X (the one that works):
protected void Chart1_Load16(object sender, EventArgs e)
{
string cs1 = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(cs1))
{
SqlCommand cmd1 = new SqlCommand("SELECT [Consumo_Medio_Real] FROM [dbo].[t_faturas]", con1);
con1.Open();
SqlDataReader rdr1 = cmd1.ExecuteReader();
var dt1 = new System.Data.DataTable();
dt1.Load(rdr1);
var enumerableTable1 = (dt1 as System.ComponentModel.IListSource).GetList();
Chart1.DataBindTable(enumerableTable1, "Consumo_Medio_Real");
And this is the code for the second (doesn´t work):
string cs = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT [Consumo_Mes_Anterior] FROM [dbo].[t_leituras]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
var dt = new System.Data.DataTable();
dt.Load(rdr);
var enumerableTable = (dt as System.ComponentModel.IListSource).GetList();
Chart1.DataBindTable(enumerableTable, "Consumo_Mes_Anterior");
Connections:
<connectionStrings>
<add name="CS1" connectionString="Data Source=ASUS;Initial Catalog=DB_SACC;Persist Security Info=True;User ID=sa;Password=1234"
providerName="System.Data.SqlClient" />
<add name="CS" connectionString="Data Source=ASUS;Initial Catalog=DB_SACC;Persist Security Info=True;User ID=sa;Password=1234"
providerName="System.Data.SqlClient" />
</connectionStrings>
I have a textbox in my winform. I want to autocomplete it with mobile number from a customer table. I have written the code but its not auto completing.
string CS = "data source=.; database=BillingSoftware; user id=sa; Password=9495640";
SqlConnection con = new SqlConnection(CS);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT Phone FROM Customers", con);
SqlDataReader rdr = cmd.ExecuteReader();
AutoCompleteStringCollection CustomerPhone = new AutoCompleteStringCollection();
while (rdr.Read())
{
CustomerPhone.Add(rdr.GetString(0));
}
txt_customerPOS.AutoCompleteCustomSource = CustomerPhone;
con.Close();
Check rdr.Read() whether you have data are not?
or call "Phone" column name
or call rdr["Phone"].ToString()
I am getting an error:
cannot convert from MySql.Data.MysqlClient.MySqlCommand to
'System.Data.SqlClient.SqlCommand' at SqlDataAdapter sda = new SqlDataAdapter(cmd);
string MyConnectionString = "Server=localhost;Database=smsjobs;Uid=root;pwd=root;";
protected void Submit_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd; connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText="select * from userdetails where db_mobi=#username and db_pass=#word";
cmd.Parameters.AddWithValue("#username", cn_mobi.Text);
cmd.Parameters.AddWithValue("#word", cn_pass.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);// getting error here
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
connection.Close();
if (dt.Rows.Count > 0)
{
Session["id"] = cn_mobi.Text;
Response.Redirect("Redirectform.aspx");
Session.RemoveAll();
}
}
You're trying to make SqlDataAdapter (the one for MS SQL) working with MySqlCommand. There is a MySqlDataAdapter, so looks like you need to be using it instead.
But anyway, this code makes no sense:
SqlDataAdapter sda = new SqlDataAdapter(cmd);// getting error here
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
You're calling DataAdapter to fill DataTable via SqlCommand, and then call that SqlCommand again with ExecuteNonQuery. That`s totally nonsense.
You need to change your code to this (probably):
string MyConnectionString = "Server=localhost;Database=smsjobs;Uid=root;pwd=root;";
protected void Submit_Click(object sender, EventArgs e) {
using(var connection = new MySqlConnection(MyConnectionString)) {
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandText="select * from userdetails where db_mobi=#username and db_pass=#word";
cmd.Parameters.AddWithValue("#username", cn_mobi.Text);
cmd.Parameters.AddWithValue("#word", cn_pass.Text);
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
Session["id"] = cn_mobi.Text;
Response.Redirect("Redirectform.aspx");
Session.RemoveAll();
}
}
}
Note the using instead of direct connection.Close()
I think you should use System.Data.OleDb;namespace and in that namespace you have same classes. Means instead of SqlConnection you should use OleDbConnection and in place of SqlDataAdapter you can use OleDbDataAdapter.
I think it should work. Hope this will help.
I think you should change
SqlDataAdapter sda = new SqlDataAdapter(cmd);
to
MySqlDataAdapter sda = new MySqlDataAdapter (cmd);
Since SqlDataAdapter is not going to be overloaded with MySqlCommand.
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