Concatenate two DataSet Column in dropdownlist DataTextField while Binding - c#

I have dropdownlist that i have to bind from back end. I am using DataSet to bind the Data but need concatenate two column data in datatextfield of Dropdownlist.
Here is my Code.
string sqlGetClass = "select * from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "brachName"+"-"+"classYear";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
if I use a single column the dropdownlist is binding fine but when concatenate them it is giving error
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'brachName-classYear'.
whene binding the Data.
Code running fine is:
string sqlGetClass = "select * from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "brachName";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
But i need to concatenate branchName and class Like M.Sc-1st Year.
Please Help. Thanks in advance.

Your best option is to specify new column in your query, and then use it as a text field:
string sqlGetClass = "select [pk_classID], [brachName] + '-' + [classYear] as [classText] from tbl_studentClass";
...
ddlClass.DataTextField = "classText";

Related

Fill combobox from SQL database with specific parameter

I have problem to get specific value from sql server with parameter can anybody explain me why it works on winfom but not on wpf and how i can fix it
my code:
private void UpdateItems()
{
COMBOBOX1.Items.Clear();
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = ds.Tables[0].Columns["FR"].ToString();
COMBOBOX1.SelectedValuePath = ds.Tables[0].Columns["FC"].ToString();
}
The program when execute this function crash with error:
System.Data.SqlClient.SqlException: 'Invalid column name
'some_specific_string'.'
the solution is
SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.constring.ToString());
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM CLIENTS where cod_cli=#cod", sqlConnection);
sqlCmd.Parameters.AddWithValue("#cod", cod_cli.Text);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
COMBOBOX1.Items.Add(sqlReader["FR"].ToString());
}
sqlReader.Close();
}
The query doesn't recognize string as parameter but adding as SQL parameter it works.
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
//Populate the combobox
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = "FR";
COMBOBOX1.SelectedValuePath = "FC";
where "FR" and "FC" are existing columns in your SELECT Query.

C# Datagridview cannot find table 0

This is my code:
SqlConnection connection = new SqlConnection(MyConnectionString2);
SqlCommand cmd2;
connection.Open();
try
{
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress);");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];
dataGridView1.DataSource = bs;
}
catch (Exception)
{
throw;
}
TxbAddEmailUser.Clear();
The problem is that my program gives me the error:
System.IndexOutOfRangeException: cannot find tabel 0;
this is my database:
table: tbl_EmailAdress
column: id, int, NOT NULL
column: Email, char(10), NULL
The insert query works, what am I doing wrong?
"Cannot find table 0" indicates that DataSet has empty tables at the first index (0), so that you can't assign data source from it.
The main problem is you're using INSERT command here:
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress);");
INSERT command is not intended to return any results for SqlDataAdapter, you need to use ExecuteNonQuery:
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress)");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
cmd2.ExecuteNonQuery();
Note that ExecuteNonQuery only returns affected rows (i.e. 1 row), and you can't assign dataGridView1.DataSource to a single integer value.
If you want to use SqlDataAdapter, you need to use SELECT statement like this example:
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("SELECT * FROM tbl_EmailAdress WHERE Email = #EmailAddress");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
adap.Fill(ds); // fill the data table from adapter
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0]; // this time the first table is not null or empty
dataGridView1.DataSource = bs;
Similar issue:
Cannot find table 0 error in C#
No need of doing this ,
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];
dataGridView1.DataSource = bs;
just use
cmd2.ExecuteNonQuery();

Error displaying data from DB to predefined columns of datagrid View on button click event

I am using the following code:
string getinputs = "SELECT ir.plu_code PLU_Code,ir.barcode Barcode,ir.product_name Product_Name FROM inventory_register ir,inventory_value iv WHERE ir.dept_id='" + textBox1.Text + "' AND ir.barcode = iv.barcode";
connection.Open();
MySqlDataAdapter adapter = new MySqlDataAdapter(getinputs, connection);
MySqlCommandBuilder cmdbuilder = new MySqlCommandBuilder(adapter);
DataTable dt = new DataTable();
adapter.Fill(dt);
BindingSource bindsrc = new BindingSource();
DataGridView datagridv = new DataGridView();
bindsrc.DataSource = dt;
datagridv.DataSource = bindsrc;
connection.Close();
I have three predefined columns in datagridview1 say 'PLU_Code', 'Barcode' and 'Product_Name'.
I want to display the result (more than one row) of the select query in the datagridview. But I am not getting any.
How do I achieve this?
Try this code:
string getinputs = "SELECT ir.plu_code PLU_Code,ir.barcode Barcode,ir.product_name Product_Name FROM inventory_register ir,inventory_value iv WHERE ir.dept_id='" + textBox1.Text + "' AND ir.barcode = iv.barcode";
connection.Open();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(getinputs, connection);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
datagridview1.DataSource = table;
connection.Close();
I got the result. I achieved two empty rows on using #user4340666 code. when i scrolled the grid i found the set of data's been added as new columns leaving predefined column cells empty. so i just cleared the columns.
dataGridView1.Columns.Clear();
string getinputs = "SELECT ir.plu_code PLU_Code,ir.barcode Barcode,ir.product_name Product_Name FROM inventory_register ir,inventory_value iv WHERE ir.dept_id='" + textBox1.Text + "' AND ir.barcode = iv.barcode";
connection.Open();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(getinputs, connection);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
datagridview1.DataSource = table;
connection.Close();
Try this code:
string getinputs = "Select Query";
connection.Open();
MySqlCommandBuilder cmdbuilder = new MySqlCommandBuilder(getinputs,connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmdbuilder);
DataTable dt = new DataTable();
adapter.Fill(dt);
DataGridView datagridv = new DataGridView();
datagridv.DataSource = dt;
datagridv.DataBind();
connection.Close();

asp.net dropDownList selected value null

I am making a school application about articles publication. In a dropdownList I want to display the value that exists in database as default pre-selected value. DropdownList conatins "emertimi" from table "kategorite". When user selects a value it saves id of "kategoria_id" in table "artikulli". Here is my code behind
if (e.Item.ItemType == ListItemType.EditItem)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection);
string Qry = "select * from kategoria";
string id = Request.QueryString["id"];
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DataSet ds2 = new DataSet();
DataSet ds3 = new DataSet();
con.Open();
da.Fill(ds);
string kategoria_id = "select kategoria_id from artikulli where id='" + id + "'";
SqlDataAdapter dk = new SqlDataAdapter(kategoria_id, con);
dk.Fill(ds2);
var kategoria_id_result = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
string emertimi = "select emertimi from kategoria where id='" + kategoria_id_result + "'";
SqlDataAdapter de = new SqlDataAdapter(emertimi, con);
de.Fill(ds3);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(emertimi).Value;
con.Close();
con.Dispose();
ds.Dispose();
ds2.Dispose();
ds3.Dispose();
da.Dispose();
dk.Dispose();
de.Dispose();
}
}
But it's showing this error: Object reference not set to an instance of an object. at this line: drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(emertimi).Value;
I guess emertimi contains a value that cannot be found in the dropdown list. Therefore, the FindByText will return null and getting the Value will result in this exception.
Test the result before you try to get the Value.
Also, instead of the separate Dispose calls, use using statements. And be aware of the SQL injection risk: use parameters instead.
That's because the item you're looking for has not been found. You should troubleshoot your code and figure out what emertimi is set to at run time.

binding a listbox

I have 4 list boxes and I have a DB as EMP with table tab1 and columns Name,EmpId, Salary ...
So I want to display salary in one of the list boxes. How do I do it???
SqlConnection con = new SqlConnection(connec);
string insert_query = "select Salary from tab1";
con.Open();
try
{
SqlCommand cmd = new SqlCommand(insert_query, con);
int exe = cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ListBox3.DataSource = ds;
ListBox3.DataBind();
}
Is this the way? I have some problems like the items are not been displayed in the list boxes.
ListBox3.DataSource = ds;
ListBox3.DataTextField = "Salary";
ListBox3.DataValueField = "EmpID";
ListBox3.DataBind();
you need to specify this before.
your code is right but u need to include some thing like this before binding..
Listbox3.Datasource=ds;
Listbox.DataTextField="Salary"
Listbox.DataValueField="EmpId"
Listbox3.Databind();

Categories