My scenario is to populate combobox from the database, display customer name, and hold a value of the id using identity increment.
When this code is run, I receive an error Procedure or function 'spSelectCustomerById' expects parameter '#id', which was not supplied.
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
//SelectCustomerById(int x);
comboBoxEx1.Items.Clear();
SqlCommand comm = new SqlCommand("spSelectCustomerByID", conn);
//comm.Parameters.Add(new SqlParameter("cust_name", cust_name));
//comm.CommandText = "spSelectCustomerByID";
comm.Parameters.Add(new SqlParameter("cust_id", SqlDbType.Int));
comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
SqlDataAdapter sdap = new SqlDataAdapter(comm);
DataSet dset = new DataSet();
sdap.Fill(dset, "cust_registrations");
if (dset.Tables["cust_registrations"].Rows.Count > 0)
{
comboBoxEx1.Items.Add("cust_registrations").ToString();
}
comboBoxEx1.DataSource = dset;
comboBoxEx1.DisplayMember = "cust_name";
How can I populate a combobox from a database?
For web combobox us comboBoxEx1.DataValueField = "cust_id";
for WPF you use comboBoxEx1.SelectedValuePath = "cust_id";
in win forms use comboBox1.ValueMember = "cust_id";
conn.Open();
//SelectCustomerById(int x);
comboBoxEx1.Items.Clear();
SqlCommand comm = new SqlCommand("spSelectCustomerByID", conn);
//comm.Parameters.Add(new SqlParameter("cust_name", cust_name));
//comm.CommandText = "spSelectCustomerByID";
comm.Parameters.Add(new SqlParameter("#id", SqlDbType.Int));
comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
SqlDataAdapter sdap = new SqlDataAdapter(comm);
DataSet dset = new DataSet();
sdap.Fill(dset, "cust_registrations");
comboBoxEx1.DataSource = dset;
comboBoxEx1.DisplayMember = "cust_name";
// Add the following line
// You do not need to add items into the combobox.
comboBoxEx1.ValueMember = "cust_id";
comboBoxEx1.DataBind();
Related
I add data to database
NpgsqlConnection conn1 = new NpgsqlConnection("Server=localhost;Port=5432;Database=test;User Id=postgres;Password=postgres;");
conn.Open();
NpgsqlCommand comm = new NpgsqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = "SELECT * FROM test";
NpgsqlDataReader dr = comm.ExecuteReader();
if (dr.HasRows)
{
dt.Load(dr);
dataGridView1.DataSource = dt;
}
comm.Dispose();
conn.Close();
so far everything is fine
but I want to add more then one query in one connection
e.g.
comm.CommandText = "SELECT * FROM test";
NpgsqlDataReader dr = comm.ExecuteReader();
// some code for view data in dataGridView1
comm.CommandText = "SELECT * FROM test1";
NpgsqlDataReader dr = comm.ExecuteReader();
// and some code for view data in dataGridView2
but I can't
or maybe use transaction but I don't know how to use it.
Easier life when you use a dataadapter:
var conn = "Server=localhost;Port=5432;Database=test;User Id=postgres;Password=postgres;"
var da = new NpgsqlDataAdapter("SELECT * FROM one", conn);
var dt = new DataTable();
da.Fill(dt);
grid1.DataSource = dt;
da = new NpgsqlDataAdapter("SELECT * FROM two", conn);
dt = new DataTable();
da.Fill(dt);
grid2.DataSource = dt;
I have a 'Create new Order' Form where I create an order which once created in now on the DB Table displayed in a datagridView.
However I am struggling to get the datagridView to auto update with the new data in it.
This is the form:
This is the table where the new order should be displaying. However only displays when i switch tables and not when the New order is created successfully.
I have tried the dataGridView.Refresh() and a bunch of other researched solutions but non seem to work.
This is my Code.
MySqlConnection conn = new MySqlConnection();
conn.Close();
var x = inputOrderTitle.Text;
Random rnd = new Random();
try
{
MySqlConnection mysqlConnection = new MySqlConnection();
connect.OpenSuccessfulDBConnection(mysqlConnection);
String query = "INSERT INTO tb_orders VALUES (#order_id, #title, #description, #scheduled_date, #deadline_date, #word_count, #editor_url, #status, #is_complete, #is_invoiced, #is_closed, #type, #ClientID, #InvoiceID, is_inprogress, #client_name, #order_cost)";
MySqlCommand cmd = new MySqlCommand(query, mysqlConnection);
cmd.Parameters.AddWithValue("#order_id", "BLG0556");
cmd.Parameters.AddWithValue("#title", "abc");
cmd.Parameters.AddWithValue("#description", "abc");
cmd.Parameters.AddWithValue("#scheduled_date", dateTimeSchedDate.Value.Date);
cmd.Parameters.AddWithValue("#deadline_date", dateTimeSubDate.Value.Date);
cmd.Parameters.AddWithValue("#word_count", 123);
cmd.Parameters.AddWithValue("#editor_url", "abc");
cmd.Parameters.AddWithValue("#status", "abc");
cmd.Parameters.AddWithValue("#is_complete", 0);
cmd.Parameters.AddWithValue("#is_invoiced", 0);
cmd.Parameters.AddWithValue("#is_closed", 0);
cmd.Parameters.AddWithValue("#type", comboBoxOrderType.Text);
cmd.Parameters.AddWithValue("#ClientID", 123);
cmd.Parameters.AddWithValue("#InvoiceID", 432);
cmd.Parameters.AddWithValue("#is_inprogress", 1);
cmd.Parameters.AddWithValue("#client_name", "abc");
cmd.Parameters.AddWithValue("#order_cost", 30.00);
int result = cmd.ExecuteNonQuery();
Application.OpenForms
.OfType<Form>()
.Where(form => String.Equals(form.Name, "NewOrder"))
.ToList()
.ForEach(form => form.Close());
MessageBox.Show("Order created successfully.");
orders.dataGridViewOrderList.Rows.Clear();
connect.GetOrderList(orders.dataGridViewOrderList);
}
Use the 'DataSource' property to bind the grid to the bunch of fetched data
SqlConnection mysqlConnection = new SqlConnection("your connection string");
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select * from tb_orders(nolock)", mysqlConnection);
if (mysqlConnection.State == ConnectionState.Closed)
mysqlConnection.Open();
da.SelectCommand.ExecuteNonQuery();
da.Fill(dt);
dataGridViewOrderList.DataSource = dt;
How can I fill a GridView in foreach because this code bring last row just not all.
foreach (int i in userdetails)
{
SqlConnection con = new SqlConnection("*****");
SqlCommand cmd = new SqlCommand("********=" + i, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvSelected.Visible = true;
gvSelected.DataSource = ds;
gvSelected.DataBind();
}
You will want to do something more like this. Only get the data in the loop.
Notice I also used a SqlParameter which is important to prevent SQL Injection and avoid syntax errors.
SqlConnection con = new SqlConnection("*****");
SqlCommand cmd = new SqlCommand("********=#id", con);
SqlParameter parId = new SqlParameter("#id", SqlDbType.Int);
cmd.Parameters.Add(parId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
foreach (int i in userdetails)
{
parId.Value = i;
da.Fill(ds);
}
gvSelected.Visible = true;
gvSelected.DataSource = ds;
gvSelected.DataBind();
Of course you should consider trying to send all ids at once if possible. You would need something like a Table Valued parameter for that.
//instantiating connection
dbConn = new SqlConnection("Data Source = local host; initial catalog=Project; Integrated Security = SSPI ");
ds = new DataSet();
//select everything from the table
dbCommand = new SqlCommand("SELECT * FROM Shops;", dbConn);
dbAdapter = new SqlDataAdapter(dbCommand);
//filling the datagrid
dbAdapter.Fill(ds, "All Shops");
dataGridView1.DataSource = ds.Tables["All Shops"];
To show data into datagrid you need to assign datasource and then use DataBind() to bind the data.
dataGridView1.DataSource = ds.Tables["All Shops"];
dataGridView1.DataBind(); // use this after assigning the datasource
private void GetResults()
{
//Establishing the MySQL Connection
MySqlConnection conn = new MySqlConnection("Database=potentiality_live;Data Source=eu;User Id=ptly;Password=phat40");
string query;
MySqlCommand SqlCommand;
MySqlDataReader reader;
MySqlDataAdapter adapter = new MySqlDataAdapter();
//Open the connection to db
conn.Open();
//Generating the query to fetch the contact details
query = "SELECT id,date_time,link FROM'sdfsdfsdf'";
SqlCommand = new MySqlCommand(query, conn);
adapter.SelectCommand = new MySqlCommand(query, conn);
//execute the query
reader = SqlCommand.ExecuteReader();
//Assign the results
GridView1.DataSource = reader;
//Bind the data
GridView1.DataBind();
}
Reference:
http://www.codeproject.com/Questions/453091/how-to-get-data-from-sql-database-to-gridview-by-c
I created a stored procedure so as to return me a table.
Something like this:
create procedure sp_returnTable
body of procedure
select * from table
end
When I call this stored procedure on the frontend what code do I need to write to retrieve it in a datatable object?
I wrote code something like the following. I basically want to know retrieving and storing table into an object of datatable. All my queries are running, but I don't know how to retrieve table into a datatable through a stored procedure
DataTable dtable = new DataTable();
cmd.Connection = _CONN;
cmd.CommandText = SPNameOrQuery;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
OpenConnection();
adp.Fill(dtTable);
CloseConnection();
Here in this code a command has been bound with the stored procedure name and its parameters. Will it be returning me a datatable from the stored procedure?
string connString = "<your connection string>";
string sql = "name of your sp";
using(SqlConnection conn = new SqlConnection(connString))
{
try
{
using(SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds, "result_name");
DataTable dt = ds.Tables["result_name"];
foreach (DataRow row in dt.Rows) {
//manipulate your data
}
}
}
catch(SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch(Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
Modified from Java Schools Example
Set the CommandText as well, and call Fill on the SqlAdapter to retrieve the results in a DataSet:
var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
Explaining if any one want to send some parameters while calling stored procedure as below,
using (SqlConnection con = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(storedProcName, con))
{
foreach (var item in sqlParams)
{
item.Direction = ParameterDirection.Input;
item.DbType = DbType.String;
command.Parameters.Add(item);
}
command.CommandType = CommandType.StoredProcedure;
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dt);
}
}
}