how can i fill a combobox using a select C# - c#

I am using the next code.
public void MostrarCombobox(ComboBox cmbIDart)
{
Command = "SELECT idArtigoAvaliar FROM dbo.PorAvaliasao WHERE (avaliado = 0) AND (idAutor ='" + Autor.id2 + "')";
SqlCommand Comm1 = new SqlCommand(Command, Conn);
SqlDataAdapter data = new SqlDataAdapter(Comm1);
SqlCommand sqlCommand = new SqlCommand();
using (Conn)
{
sqlCommand = Conn.CreateCommand();
sqlCommand.CommandText = Command;
SqlDataAdapter sda = new SqlDataAdapter(sqlCommand.CommandText, Conn);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
//Criar uma tabela para receber os dados
DataTable dTable = new DataTable();
//Preencher a tabela
sda.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
cmbIDart.DataSource = bSource;
Conn.Close();
}
}
My problem is that when I am starting to call the ComboBox, it shows System.Data... and I want them to show the value.
What am I doing wrong?

I think in your combobox rows look like showing like;
System.Data.DataRowView
System.Data.DataRowView
System.Data.DataRowView
System.Data.DataRowView
System.Data.DataRowView
You need to set your Combobox DisplayMember and ValueMember properties.
If this is not fix your problem, try to make things more clear dynamically.
Combobox1.Items.Clear();
string Command = "SELECT idArtigoAvaliar FROM dbo.PorAvaliasao WHERE (avaliado = 0) AND (idAutor ='" + Autor.id2 + "')";
SqlCommand cmd = new SqlCommand(Command, Conn);
cmd.CommandText = Command;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Combobox1.Items.Add(dr["idArtigoAvaliar"].ToString());
}

Related

How to retrieve data from postgres to textbox in c#.net

I want to retrieve data from postgres db into textbox in C# without using grid.
Here is the running successful code by using grid which I had tried:
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM student_folio";
cmd.CommandType = CommandType.Text;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cmd.Dispose();
connection.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
I get error when build when I want to retrieve it into textbox:
"cannot apply indexing with [] to an expression of type 'NpgsqlDataAdapter'"
Here is my block of code:
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = ("SELECT f_name FROM student_folio WHERE id = 1");
cmd.CommandType = CommandType.Text;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
txtFname.Text = da["f_name"].ToString();
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
A DataAdapter is not an array of rows you can loop into.
Look at your first code block : you must fill a DataTable from your adapter and then read through the Rows property of this DataTable.
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
txtFname.Text = dt.Rows[0]["f_name"].ToString();
}
You could also do this :
foreach (System.Data.DataRow row in dt.Rows)
{
txtFname.Text = row["f_name"].ToString();
}
And please, remove the cmd.ExecuteNonQuery(); line, it is useless here
try this . .
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
NpgsqlDataReader dr=null;
cmd.Connection = connection;
cmd.CommandText = ("SELECT f_name FROM student_folio WHERE id = 1");
cmd.CommandType = CommandType.Text;
dr=cmd.ExecuteReader();
while(dr.HasRows)
{
while(dr.Read())
{
txtFname.Text = da["f_name"].ToString();
}
}
connection.Close();

How to display the proper data?

I have 2 datagridviews now i want to select a column named "Name" in the first datagridview and us it as the WHERE in my query to Select values from a table and put it in the other datagridview.
SqlCommand cmd = new SqlCommand();
cmd = ss.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
ss.Open();
cmd.CommandType = CommandType.Text;
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "' ";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
dgvSign.DataSource = dt;
ss.Close();
}
but it gives me error when there is null and it is only selecting the first row in the first datagridview.
You create in each foreach-loop a new DataTable and therefore it will always just have one Value. So you have to create it before the foreach-loop.
And make sure you check the Values you want to use before using them.
With this easy if-condition, there won't be any problems.
Edit1:
This code snippet is working just fine.
Just change the ConnectionString and you are done.
DataTable dt = new DataTable();
string error;
using (SqlConnection con = new SqlConnection(#"Data Source=SERVER;Initial Catalog=DATEBASE; User ID=USERNAME; Password=PASSWORD"))
{
SqlCommand cmd = new SqlCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '";
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
Query += row.Cells[4].Value.ToString();
}
Query += "'";
try
{
cmd = new SqlCommand(Query, con);
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
catch (Exception ex)
{
error = ex.Message;
}
}
}
dgvSign.DataSource = dt;

Update button won't update data on DataGridView C#

try
{
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Dsn=mdc;" +
"Uid=root;" +
"Pwd=;";
OdbcCommand cmd = new OdbcCommand("UPDATE tbl_delivery SET Address = #Address, AssetNumber = #AssetNumber, Contact = #Contact, DRNumber = #DRNumber, InvoiceNumber = #InvoiceNumber, ItemQty = #ItemQty, PONumber = #PONumber, ReceivedBy = #ReceivedBy, Supplier = #Supplier WHERE No = #No;", conn);
//DataRowView drv = (DataRowView) comboBox1.SelectedValue;
cmd.Parameters.AddWithValue("#No", noTextBox.Text);
cmd.Parameters.AddWithValue("#AssetNumber", assetNumberTextBox.Text);
cmd.Parameters.AddWithValue("#Contact", contactTextBox.Text);
cmd.Parameters.AddWithValue("#DRNumber", dRNumberTextBox.Text);
cmd.Parameters.AddWithValue("#InvoiceNumber", invoiceNumberTextBox.Text);
cmd.Parameters.AddWithValue("#ItemQty", itemQtyTextBox.Text);
cmd.Parameters.AddWithValue("#PONumber", pONumberTextBox.Text);
cmd.Parameters.AddWithValue("#ReceivedBy", receivedByTextBox.Text);
cmd.Parameters.AddWithValue("#Supplier", supplierTextBox.Text);
cmd.CommandType = CommandType.Text;
OdbcDataAdapter ds = new OdbcDataAdapter(cmd);
ds.SelectCommand = cmd;
System.Data.DataTable dtable = new System.Data.DataTable();
ds.Fill(dtable);
tbl_deliveryDataGridView.DataSource = dtable;
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("update successful");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Whenever I click one data from datagridview and changed it using textbox, it won't update.
If your query gives the expected result, and the data get updated in then database. then you need to ReBind the grid to load the updated data to the grid.
let Gv_delivery be your datagrid then the code will be like the following:
Gv_delivery.Rebind
the code to be attached to your code after the update execute.
You want to fill your DataTable with OdbcDataAdapter and update command.
EDIT:
Here are cuts from your code:
//here your cmd is set to UPDATE
OdbcCommand cmd = new OdbcCommand("UPDATE tbl_delivery SET Address = #Address, AssetNumber = #AssetNumber, Contact = #Contact, DRNumber = #DRNumber, InvoiceNumber = #InvoiceNumber, ItemQty = #ItemQty, PONumber = #PONumber, ReceivedBy = #ReceivedBy, Supplier = #Supplier WHERE No = #No;", conn);
//here your SelectCommand is set to UPDATE
ds.SelectCommand = cmd;
//here you fill your datatable
ds.Fill(dtable);
You should set your SelectCommand and UpdateCommand correctly. You cannot fill datatable with UPDATE.

How to get ID against selected value of Dropdownlist C#

How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.

How to get data from SQL database to store in combo box - C#

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";
}

Categories

Resources