am trying to get the selected item from the database, but its not displaying nothing
code behind:
private void bindRows()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand("select id, message from Dropdown", connection);
SqlDataReader reader = cmd.ExecuteReader();
reader.Close();
SqlDataAdapter adapter = new SqlDataAdapter("select id, message from Dropdown", connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
DdlRegister.DataSource = ds;
DdlRegister.DataTextField = "message";
DdlRegister.DataValueField = "id";
DdlRegister.DataBind();
DdlRegister.Items.Insert(0, new ListItem("I Want", "0"));
connection.Close();
}
catch (Exception e)
{
}
}
code of buttonclick
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string selectCommand = "Insert into Register (name,designation,company,mobile,email,message) values(#name,#designation,#company,#mobile,#email,#message);";
SqlCommand cmd = new SqlCommand(selectCommand, connection);
cmd.Parameters.AddWithValue("#name", txtname.Text.Trim());
cmd.Parameters.AddWithValue("#designation", txtdesignation.Text.Trim());
cmd.Parameters.AddWithValue("#company", txtcompany.Text.Trim());
cmd.Parameters.AddWithValue("#mobile", txtmobile.Text.Trim());
cmd.Parameters.AddWithValue("#email", txtemail.Text.Trim());
cmd.Parameters.AddWithValue("#message", DdlRegister.SelectedItem.Text.Trim());
int cnt = cmd.ExecuteNonQuery();
if (cnt > 0)
{
ShowMessage("Registeration is done");
}
Response.Redirect("Index.aspx");
connection.Close();
}
catch (Exception ex)
{
}
design
<asp:DropDownList ID="DdlRegister" runat="server" CssClass="form-control ddl " OnSelectedIndexChanged="DdlRegister_SelectedIndexChanged" AutoPostBack="true" >
</asp:DropDownList>
private void bindRows()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select id, message from Dropdown", connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
DdlRegister.DataSource = ds;
DdlRegister.DataTextField = "message";
DdlRegister.DataValueField = "id";
DdlRegister.DataBind();
DdlRegister.Items.Insert(0, new ListItem("I Want", "0"));
connection.Close();
}
catch (Exception e)
{
}
}
try something like this
string mainconn = ConfigurationManager.ConnectionStrings["MY"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[sortcompany]";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
Company.ValueMember = "company_name";
Company.DisplayMember = "company_name";
Company.DataSource = dt;
Related
Why do I get blank rows when I retrieve rows from MySQL database to dataGridView? I end up getting the amount of rows but its empty (it has no text).
this is my code so far:
private void button2_Click(object sender, EventArgs e)
{
string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("Select * FROM TopShineDB.Table1 ;", conDataBase);
using (MySqlConnection conn = new MySqlConnection(constring))
{
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dt = new DataTable();
sda.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
sda.Update(dt);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I tried below code sample to get data from database and bind to datagridview.
var ConnectionString = "your ConnectionString";
MySqlConnection connect = new MySqlConnection(ConnectionString);
MySqlCommand cmd = new MySqlCommand("your query");
connect.Open();
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable dt = new DataTable();
dt = DtSet.Tables[0];
dataGridView1.DataSource = DtSet.Tables[0];
connect.Close();
Try This:
private void BindGrid()
{
string conString = #"Data Source=localhost;port=3306;Initial Catalog=TopShineDB;User Id=root;password=0159";
using (MySqlConnection con = new MySqlConnection(conString))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Table1", con))
{
cmd.CommandType = CommandType.Text;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
*Just Clear your Columns you define in DataGridView *
private void button2_Click(object sender, EventArgs e)
{
string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("Select * FROM TopShineDB.Table1 ;", conDataBase);
using (MySqlConnection conn = new MySqlConnection(constring))
{
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Columns.Clear();
dataGridView1.DataSource = bs;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
c#
I am trying to populate a dropdownlist from sql server by using classes as shown below. The code breaks down when it comes to bind the data into the dropdown list. It gives an error on giving the dropdownlist the dataValueField and datatTextField.
HTML... a.aspx
<asp:DropDownList ID="NationalityDropDownList" runat="server" >
</asp:DropDownList>
C#... a.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Classes.Nationality PossibleNationality = new Classes.Nationality();
if (!Page.IsPostBack)
{
DataTable dataTable = PossibleNationality.getNationality();
NationalityDropDownList.DataSource = dataTable;
NationalityDropDownList.DataValueField = "ID";
NationalityDropDownList.DataTextField = "Nationality";
NationalityDropDownList.DataBind();
}
}
Nationality.cs
public class Nationality
{
public DataTable getNationality()
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["InformationConnection"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spGetAllUsers", conn);
comm.CommandType = CommandType.StoredProcedure;
DataTable dataTable;
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
dataTable = new DataTable();
da.Fill(dataTable);
}
finally
{
conn.Close();
}
return dataTable;
}
}
SQL procedure....
ALTER PROCEDURE [dbo].[spGetNationalities]
AS
BEGIN
select * from Nationality;
END
This line of code in your getNationalitymethod...
comm = new SqlCommand("spGetAllUsers", conn);
...should be this instead
comm = new SqlCommand("spGetNationalities", conn);
Databinding should work if your Nationality table has columns ID and Nationality
if (!Page.IsPostBack)
{
try
{
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}
}
catch (Exception Ex)
{
Console.WriteLine("Error: " + Ex.Message);
}
GetData();
}
I have added a new value into my combobox and it should be displayed based on what I have in my database. But unfortunately, the new value does not display out. Below are my codes.
string dbConn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\SONY\\Desktop\\FinalYearProject\\FinalYearProject\\bin\\Debug\\housewife.mdf;Integrated Security=True;User Instance=True";
void fill_Combo() {
SqlConnection conn = new SqlConnection(dbConn);
try {
conn.Open();
string query = "Select * From Food";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
string name = dr.GetString(1);
comboBox1.Items.Add(name);
}
conn.Close();
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
You should be using an observable collection as the data source and binding to that collection. See Add items to comboBox in WPF
Hi please try something like this, hope it helps
string dbConn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\SONY\\Desktop\\FinalYearProject\\FinalYear Project\\bin\\Debug\\housewife.mdf;Integrated Security=True;User Instance=True";
void fill_Combo() {
SqlConnection conn = new SqlConnection(dbConn);
try {
conn.Open();
string query = "Select * From Food";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds)
combobox1.DataSourse = ds;
combobox1.DisplayMember = "fieldname";
combobox1.ValueMember = "fieldname";
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
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";
}
I have a data base in SQL Server 2008 and connecting it in WPF application.I want to read data from table and show in datagrid. Connection is successfully created but when I show it in grid,it show db error(Exception handling).
This is what I am doing.Thanks in advance.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
It shows connected when i comment the line sda.Fill(dt);
Your SqlCommand doesn't know you opened the connection- it requires an instance of SqlConnection.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
You don't assign the command any connection. You open the connection then create a command, but don't link the two.
Try something like:
SqlConnection conn = new SqlConnection(#"Server(local);Database=Sample_db;Trusted_Connection=Yes;");
conn.Open();
string sql= "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(sql);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
Assign Connection Object to SqlCommand Object.
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandTimeout = 15;
command.CommandType = CommandType.Text;
command.CommandText = queryString;
connection.Open();
//Perfom desired Action
}
Add thisConnection as 2nd parameter in
Sqlcommand cmd = new SqlCommand(Get_Data, thisConnection)
try {
string connectionstring = "#"
Server = (local) Database = Sample_dbTrusted_Connection = Yes;
"";
SqlConnection thisConnection = new SqlConnection(connectionstring);
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data, thisConnection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);`
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
} catch {
MessageBox.Show("db error");
}
I use this code with Oracle and hope it will help you.
First add reference Oracle.DataAccess then add namespace using Oracle.DataAccess.Client;
And using the following code
try
{
string MyConString = "Data Source=localhost;User Id= yourusername;Password=yourpassword;";
using (OracleConnection connection = new OracleConnection(MyConString))
{
connection.Open();
sqldb1 = "select * from DEMO_CUSTOMERS;";
using (OracleCommand cmdSe1 = new OracleCommand(sqldb1, connection))
{
DataTable dt = new DataTable();
OracleDataAdapter da = new OracleDataAdapter(cmdSe1);
da.Fill(dt);
db1.ItemsSource = dt.DefaultView;
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
XAML code:
<DockPanel>
<DataGrid Margin="10.0" DockPanel.Dock="Left" Name="db1" AutoGenerateColumns="True" >
</DataGrid>
</DockPanel>
public DataTable Execute(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable dt = new DataTable();
sda.SelectCommand = command;
command.Connection = connection;
connection.Open();
sda.Fill(dt);
connection.Close();
if (dt != null && dt.Columns.Count > 0)
return dt;
else
return null;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
else
{
Console.WriteLine("Network is disconnect");
return null;
}
return null;
}
or :
public void ExecuteNonQuery(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}