Salam Alekom .
I have comboBox filling it from database as
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand scm = new SqlCommand();
scm.Connection = con;
scm.CommandText = "select * from com";
SqlDataAdapter adpt = new SqlDataAdapter(scm);
DataTable dt = new DataTable();
adpt.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = dt.Columns["com_name"].ToString();
comboBox1.ValueMember = dt.Columns["com_id"].ToString();
Where filling with all data that store in the table from database.
This comboBox use also to insert to another table in database
This also poses no problem
The problem when making search in table to get some data. I need to get the text value that store in table and equal to text value of comboBox and sort it in position 0 of this comboBox
I made the search no problem but what property or method that allow me to put the value in position 0 with out affecting the other values that be in combobox
SqlConnection con = new SqlConnection(strcon);
con.Open();
using(SqlCommand scm2 = new SqlCommand())
{
scm2 .Connection = con;
scm2.CommandType = CommandType.StoredProcedure;
scm2 .CommandText = "SP_retrieve_data";
scm2.Parameters.AddWithValue ("#id", textBox1.Text);
SqlDataReader dr = scm2.ExecuteReader();
while (dr.Read())
{
comboBox1. = dr["com_name"].ToString();//what code accept the value
}
}
Related
I'm trying to insert some records to 2 tables at same event
private void Btngravar_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("server=localhost;user id=root;database=saude;Password=");
conn.Open();
MySqlCommand objcmd = new MySqlCommand("insert into dispensacao (DESTINATARIO,COD_UNIDADE,COD_DEPARTAMENTO,DATA,SOLICITANTE,DEFERIDO_POR) values(?,?,?,?,?,?)", conn);
objcmd.Parameters.Add("#DESTINATARIO", MySqlDbType.VarChar, 45).Value = Cmbdestinatario.Text;
objcmd.Parameters.AddWithValue("#COD_UNIDADE", string.IsNullOrEmpty(Txtcodigounidade.Text) ? (object)DBNull.Value : Txtcodigounidade.Text);
objcmd.Parameters.AddWithValue("#COD_DEPARTAMENTO", string.IsNullOrEmpty(Txtcodigodep.Text) ? (object)DBNull.Value : Txtcodigodep.Text);
DateTime fdate = DateTime.Parse(Txtdata.Text);
objcmd.Parameters.Add("#DATA", MySqlDbType.DateTime).Value = fdate;
objcmd.Parameters.Add("#SOLICITANTE", MySqlDbType.VarChar, 45).Value = Txtsolicitante.Text;
objcmd.Parameters.Add("#DEFERIDO_POR", MySqlDbType.VarChar, 45).Value = Txtdeferido.Text;
objcmd.ExecuteNonQuery();
conn.Close();
conn.Open();
objcmd = new MySqlCommand("insert into produtos_disp(COD_DISPENSACAO,COD_PRODUTO,PRODUTO,QUANTIDADE) values (?,?,?,?)", conn);
string selectid = "select ifnull (max(ID),1) from dispensacao";
objcmd = new MySqlCommand(selectid, conn);
MySqlDataReader reader = objcmd.ExecuteReader();
if (reader.Read())
{
Txtcodigo.Text = reader.GetString("ID");
}
//Txtcodigo.DataBindings.Add("Text", dtid, "ID");
objcmd.Parameters.AddWithValue("#COD_DISPENSACAO", Txtcodigo.Text);
objcmd.Parameters.AddWithValue("#COD_PRODUTO", dtproddisp.Rows[0][0]);
objcmd.Parameters.AddWithValue("#PRODUTO", dtproddisp.Rows[0][1]);
objcmd.Parameters.AddWithValue("#PRODUTO", dtproddisp.Rows[0][2]);
Code from the comment
string selectQuery = "SELECT * from departamento";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(reader);
Cmbdestinatario.DisplayMember = "nome";
Cmbdestinatario.ValueMember = "CODIGO";
Cmbdestinatario.DataSource = dt2;
Txtcodigodep.DataBindings.Add("Text", dt2, "CODIGO");
The first part is working, I can see records inserted on dispensacao table, but the second isn't working, error:
Could not find specified column in results: ID
and I need to get products from datagridview,
App screen:
MySQL Dispensacao table:
My problem now is inserting those selected products from datagridview on database and get the id from dispensacao to insert on products table,
If you want to insert more rows in a database(from what I known), you should add a checkbox in a DataGridView Column and store checked rows to a list. Then you should use a for loop to insert each data to Database by list values.
If you want the code please comment me.
I am struggling to make my dataGrid viev results of query. Connection with database is fine. Here is sample of my code:
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = "properConnectionString"
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * FROM WORKERS";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
using (OracleDataAdapter orclDataAdapter = new OracleDataAdapter(cmd))
{
DataTable dt = new DataTable();
orclDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Assuming that your call to the Oracle database is actually returning data, you're missing the databind statement on the gridview. Add this:
dataGridView1.DataBind();
place it right after the dataGridView1.DataSource = dt; line of code.
//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 want to populate data from a SQL Server database from many columns to many textboxes .. I have a code to populate just one box .. can someone edit my code... I want to pull data and show it in Name, Address, Telephone No and Date ... plz help .. this code works for only one textbox..
Thanks in advance
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select * From PersonalUsers ", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
Name.Text = DR1.GetValue(0).ToString();
}
while (DR1.Read())
{
if(DR1.GetName() == "YourSQLColumnName")
{
YourTextBox.Text = (string) DR1["YourSQLColumnName"];
}
// Your Other textboxes and columns which you want to match should follow as this template
}
SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, _conn);
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable tbl = new System.Data.DataTable("Results");
tbl.Load(rdr);
if (tbl.Rows.Count > 0)
Name.Text = tbl.Rows[0]["column_name"].ToString();
string cs=System.Configuration.ConfigurationManager.ConnectionString["DBCS"].ConnectionString;
using(OracleConnection con=new OracleConnection(cs))
{
sql="select empname from Emp where empno='"+empno+"'";
OracleCommand cmd = new System.Data.OracleClient.OracleCommand(sql,con);
con.Open();
OracleDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
{
EmpName.Text=Convert.ToString(rd["empname"]);
}
}
I assume that you would like to take care of both more rows and more columns.
Try to specify the columns. It works without, but the performance is better if you do so.
I assume you have a class called PersonalUser with the specifed properties.
It is also nice to have it in an sorted order, so I added that
public List<PersonalUser> FetchMyData()
{
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select Name, Address, TelephoneNo,Date From PersonalUsers order by Name", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
var result = new List<PersonalUser>();
while (DR1.Read())
{
result.Add(new PersonalUser {
Name = DR1.GetString(0);
Address= DR1.GetString(1);
TelephoneNo = DR1.GetString(2);
Date = DR1.GetString(3)
}
);
}
return result;
}
I would also, if the need is getting much complex than this, conidering using Entity Framwork..
Object reference not set to an instance of an object.
This is the error which i m getting while i trying to delete .. row from my grid view
this is in .. page_ load
gvDetails.DataSource =myBl.DeleteAllCountry(int.Parse(gvDetails.SelectedRow.ToString()));
on data access layer
public DataTable DeleteCountry(int country_id)
{
DataTable dltcontry = new DataTable();
SqlConnection con = new SqlConnection(#"Data Source=a8-pc\sqlexpress;Integrated Security=True");
SqlDataAdapter da;
try
{
SqlCommand cmd = new SqlCommand();
cmd.connection= con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_DeleteCountry";
con.Open();
da = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("country_id", #country_id);
cmd.ExecuteNonQuery();
da.Fill(dltcontry);
con.Close();
}
and in business layer the code is like
public DataTable DeleteAllCountry(int country_id)
{
return mydtLayer.DeleteCountry(country_id);
}
First thing to correct, you need to set connection to your command
cmd.Connection =con;
or in the constructor as below
SqlCommand command = new SqlCommand(
queryString, connection);
Another problem is you try to convert selected gvDetails.SelectedRow to int value
check gvDetails.selectedRows.Count before you get value of selected row
if you have selection you can then get cell valu of your country_id column as below
gvDetails.SelectedRow.cells("country_id").Text
now you can convert this to a int value by using int.TryParse and if it is success send to your BL function to delete the record