create a dropdown list in c# .net server side - c#

I trie to create a dropdown list in c# .net server side ... but this is not working .. anyone know what is it going wrong here?
string conncetionStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection msSQLConnectoin = new SqlConnection(conncetionStr);
SqlCommand msSQLCommand = msSQLConnectoin.CreateCommand();
msSQLCommand.CommandText = "app_Event_Type_Select";
msSQLConnectoin.Open();
SqlDataReader msDataReader = msSQLCommand.ExecuteReader();
while (msDataReader.Read())
{
dropDown.DataSource = msDataReader["Name"].ToString();
dropDown.DataTextField = msDataReader["Name"].ToString();
dropDown.DataValueField = msDataReader["EventTypeID"].ToString();
dropDown.DataBind();
}

string conncetionStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection msSQLConnectoin = new SqlConnection(conncetionStr);
SqlCommand msSQLCommand = msSQLConnectoin.CreateCommand();
msSQLCommand.CommandText = "app_Event_Type_Select";
msSQLConnectoin.Open();
SqlDataReader msDataReader = msSQLCommand.ExecuteReader();
dropDown.DataSource = msDataReader;
dropDown.DataTextField = "Name";
dropDown.DataValueField = "EventTypeID";
dropDown.DataBind();
msSQLConnectoin.Close();
msSQLConnectoin.Dispose();
dropDown.Items.Insert(0, "--Select Name--");
}
Replace msDataReader["Name"].ToString() with your data reader name msDataReader

Sample Code:
protected void Page_Load(object sender, EventArgs e)
{
bindDropdownlist()
}
public void bindDropdownlist()
{
SqlDataAdapter dap = new SqlDataAdapter("select colmn1,colmn2 from table", con);
DataSet ds = new DataSet();
dap.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "colmn1";
DropDownList1.DataValueField = "colmn2";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "..select...");
}

I believe the DataTextField and DataValueField should be string representations of the property you've bound, see this related post:
dropDown.DataSource = msDataReader;
dropDown.DataTextField = "Name";
dropDown.DataValueField = "EventTypeID";

Read here
The DataSource property is supposed to be set with an object containing all the informations the control needs to be bound to. The DataTextField and the DataValueField should be a reference to actual data on the DataSource object. A simple way to achieve your goal could be to prepare a DataTable using Text and Value fields and then bind the control this way:
dropDown.DataSource = dt;
dropDown.DataTextField = "Text";
dropDown.DataValueField = "Value";
dropDown.DataBind();
Here on the msdn web site you'll find your same scenario.

Related

C#/ASP.NET gridview databind dropdownlist index changed

I am new to .net world and I could not figure out why the below code does not work. I have a dropdownlist populated with DEPARTMENT_NAME and value as DEPARTMENT_ID. I have a gridview which populates the employees data based on department_id selected from dropdown list. I have written the following code but the gridview is not populating. Can someone please help what I am doing wrong here.
protected void ddDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
OracleConnection oConn = new OracleConnection(connStr);
oConn.Open();
string SqlText = "Select * from employees where department_id = :department_id";
OracleCommand cmd = new OracleCommand(SqlText, oConn);
cmd.CommandType = CommandType.Text;
OracleParameter p_department_id = new OracleParameter();
p_department_id.OracleDbType = OracleDbType.Varchar2;
p_department_id.Value = ddDepartments.SelectedItem.Value;
cmd.Parameters.Add(p_department_id);
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
DataTable dtEmployees = new DataTable();
adapter.Fill(dtEmployees);
gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();
dtEmployees.Dispose();
adapter.Dispose();
cmd.Dispose();
oConn.Close();
oConn.Dispose();
}
You need to use a Session variable to persist the gridView datasource on Postback which is sent by the dropdownlist.
So right after:
gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();
Add:
Session("gvDS") = gvEmployees.DataSource;
In the page Load() method:
if (Session["gvDS"] != null && IsPostBack)
{
gvEmployees.DataSource = Session["gvDS"];
gvEmployees.DataBind();
}
else
BindGridView(); // you initial gvEmployees binding method
Please see my answer #:
Asp.net Web Forms GridView Dynamic Column Issue

show data in Listbox c# from sql

I have this code to show data from SQL to listbox in c#
public DataTable get_mada_listbox()
{
DAL.DATAACSESSLAYER dal = new DAL.DATAACSESSLAYER();
dal.open();
DataTable dt = new DataTable();
dt = dal.selectData("get_mada_listbox", null);
dal.close();
return dt;
}
When I call the function:
BL.cls_product prd = new BL.cls_product();
listBox1.DataSource = prd.get_mada_listbox();
The listbox should show
system.data.data row view.
How can I solve it?
i solve my problem by add
listBox1.DisplayMember = "mada_name";
next this
listBox1.DataSource = prd.get_mada_listbox();
thx
This should be your method:
void get_mada_listbox()
{
var connection = ConfigurationManager.ConnectionStrings[name].ConnectionString;
using (SqlConnection connsql = new SqlConnection(connString))
{
connsql.Open();
// Sql Adapter
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter("SELECT * FROM DataTable", connection))
{
// fill a data table
var data_table = new DataTable();
sqlAdapter.Fill(t);
// Bind the table to the list box
listBox1.DisplayMember = "mada_name";
listBox1.ValueMember = "mada_value";
listBox1.DataSource = data_table;
}
}
}

ComboBox SelectedItem shows System.Data.DataRowView

I insert data from my database to combobox, and now I want to display value of this combobox into label, but every time instead of getting value of combobox, I get System.Data.DataRowView in my label.
I use this code for connection, it works fine:
OracleConnectionStringBuilder sb = new OracleConnectionStringBuilder();
sb.DataSource = "localhost";
sb.UserID = "library";
sb.Password = "library";
OracleConnection conn = new OracleConnection(sb.ToString());
conn.Open();
OracleDataAdapter TITLES = new OracleDataAdapter("SELECT NAME FROM TITLE", conn);
DataTable dt = new DataTable();
TITLES.Fill(dt);
cmbBooks.DisplayMember = "NAME";
cmbBooks.DataSource = dt;
conn.Close();
And then I want to get SelectedItem using this code:
label1.Text = cmbBooks.Items[cmbBooks.SelectedIndex].ToString();
How to solve it?
You can use the GetItemText method:
label1.Text = cmbBooks.GetItemText(cmbBooks.SelectedItem);

How to send selected data from a dropdownlist to the corresponding table in mysql?

So this what I have done so far :
//inserting enrolment details
string input_club = DropDownList1.SelectedItem.Text;
string enrol_mysql = "INSERT INTO enrolment_details(child_id,club_name) VALUES (#child_id, #club_name)";
long id = newchild.LastInsertedId;
MySqlCommand enrol = new MySqlCommand(enrol_mysql, connection);
enrol.CommandText = enrol_mysql;
enrol.Parameters.AddWithValue("#child_id", id);
enrol.Parameters.AddWithValue("#club_name", input_club);
enrol.ExecuteNonQuery();
The problem occurs when if for example user selects the club, the correct option does not appear on the table. (please look at the screen shots I have inserted)
EDIT: This has been called on a button click :
protected void registerEventMethod(object sender, EventArgs e)
{
registerUser();
Server.Transfer("~/Registration_Login.aspx");
}
private void registerUser()
{...}
Additionally the options shown in the dropdownlist are retrieved from another table. Here is the code if for any relevance :
// Retriving club data from club_detail table from mysql
MySqlCommand clubdata = new MySqlCommand("SELECT club_id,club_name FROM club_details", connection);
DropDownList1.DataSource = clubdata.ExecuteReader();
DropDownList1.DataTextField = "club_name";
DropDownList1.DataValueField = "club_id";
DropDownList1.DataBind();
Many thanks for the help.
var sqlQry = "SELECT club_id,club_name FROM club_details";
var da = new MySqlDataAdapter(sqlQry, connection);
var ds = new DataSet();
da.Fill(ds, "ClubDetails");
DropDownList1.DataSource = ds.Tables["ClubDetails"];
DropDownList1.DataTextField = "club_name";
DropDownList1.DataValueField = "club_id";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select Item", "0"));
you may also want to change this string input_club = DropDownList1.SelectedItem.Text;
to test off of
var input_club = DropDownList1.SelectedValue;

How to set combobox value to null or empty while loading data to it from database in c#.net

I have a windows form coded in c#..
the problem is I have a combobox which is loaded values from database,and that code has written in LOAD form..
so,my form's combobox values are generated automatically to it and the Initial combobx text is loaded to it..
I want to set combobox initial text or value should be empty or null..
please help me to solve it..
Thanx in advance
my code is as follows
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name,image from Employee_Details", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("employee_id", typeof(string));
dt.Columns.Add("employee_name", typeof(string));
dt.Load(dtr);
//Convert.ToString.comboBox1.Items.Insert("", 0);
comboBox1.DisplayMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
//dateTimePicker1.Enabled = true; ;
cn.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
Add this line after you set your datasource to db:
comboBox1.SelectedItem = null;
Or
comboBox1.SelectedItem = -1;
do not make it null, better to writer it Select as selected value.
`dt.Load(dtr);
DataRow drow = dt.NewRow();
drow[0] = "-1";
drow[1] = "Select";
drow[2] = string.Empty;
dt.Rows.InsertAt(drow, 0);
dt.AcceptChanges();
comboBox1.DisplayMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;`

Categories