binding a listbox - c#

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();

Related

I connot able to filter the current user record using c# and MS Access DB

I connot able to filter the current user record. I want to display the data of current user only. But I did not understand how to handl query.
here is the ss of login.
As I selected Student, and username =50 and pass=50 ,
and when i press he show button this will display all the record but i want only current user data :
here is the code :
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
OleDbDataAdapter sda = new OleDbDataAdapter(#"SELECT student.s_id, student.f_name, student.l_name, student.email, student.address, course.c_id, course.cname, resultdate.resultgrade FROM ((student INNER JOIN resultdate ON student.s_id = resultdate.s_id) INNER JOIN course ON resultdate.c_id = course.c_id)", conn);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
//dataGridView1.Text = dt.Rows.Count.ToString();
conn.Close();
Paste this code in your combobox.
con.Open();
string query = “ select* from student where student.s_id = ’”
+combobox1.SelectedItem.ToString() + “’”;
OleDbDataAdapter sda = new OleDbDataAdapter(query, con);
OleDbCommandBuiler builer = new OleDbCommandBuiler(da);
var ds = new DataSet();
sda.Fill(ds);
datagridview1.Datasource = ds.Table[0];
conn.Close();

Updating Data GridView using the selected value inside the dropdown list

I have a dropdownlist and a gridview.. Dropdown list contains the list of the tables I have in my database. What I want is, when I select a particular table name from the dropdownlist, I want all the columns and data inside that particular table display inside the gridview.
This is my code...
Code for displaying the list of tables inside the dropdown is success.. But to bind the columns and data inside the gridview is not success..
Please Help me...
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT table_name FROM INFORMATION_SCHEMA.TABLES", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "table_name";
DropDownList1.DataValueField = "table_name";
DropDownList1.DataBind();
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.columns where table_name='+ DropDownList1.selecteditem.text +'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
//+DropDownList1.selecteditem.text +
GridView1.DataBind();
con.Close();
}
}
This is a bad idea on several levels. First you are wide open to SQL injection. Second, you are giving everyone full view access to every column and row of every table.
But the reason you are not getting data is because the select string does not make sense. It should look like this
"SELECT * FROM INFORMATION_SCHEMA.columns where table_name='" + DropDownList1.SelectedValue + "'"
But this is how a proper sql connection should look like.
//create a new datatable
DataTable dt = new DataTable();
//create the string that hold the query including token
string query = "SELECT * FROM INFORMATION_SCHEMA.columns where table_name = #TableName";
//create a new database connection
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandType = CommandType.Text;
//replace the token with the correct value
command.Parameters.Add("#TableName", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;
//open the connection
connection.Open();
//load the data of the select into the datatable
dt.Load(command.ExecuteReader());
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//but you can also skip the datatable and bind directly to the gridview
GridView1.DataSource = command.ExecuteReader();
GridView1.DataBind();
}

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();

select the date only from date datatype to show in dropdown list

I make a query under dropdown list to show the date from date datatype.
Here is the query/code in the visual studio.
SqlDataAdapter adapter = new SqlDataAdapter("select cast(timestamp_Instance as varchar(12)) from Instance1", con);
con.open();
i tried above query and the output is correct.
Below is the screenshot of the table
table
Below is screenshot of the output in dropdown list
output
This my code to bind the values in the dropdown list but i got an error after trying this. The erro is :System.Data.DataRowView' does not contain a property with the name 'timestamp_Instance'
SqlDataAdapter adapter = new SqlDataAdapter("select cast(timestamp_Instance as varchar(12)) from Instance1", con);
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataValueField = "timestamp_Instance";
DropDownList1.DataBind();
con.Close();
try this
select cast(timestamp_Instanc as varchar(12))
So your code will look like :
SqlDataAdapter adapter = new SqlDataAdapter("select cast(timestamp_Instanc as varchar(12)) from table1", con); con.open();
As a wild guess, I'll suggest you to typecast your value as DateTime and take only the Date part. For example:
var dateTime = DateTime.Now;
var onlyDate = DateTime.Date;

Concatenate two DataSet Column in dropdownlist DataTextField while Binding

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

Categories