Set selected value of DropDownList based on database - c#

I have a dropdownlist in a gridview and when the textbox is changed, I would like the selected value in the dropdownlists (three separate ones in total) to match the data in the database. The code in the textbox changed event is below:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
DropDownList ddl = new DropDownList();
string connectionString = ConfigurationManager.ConnectionStrings["*******"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
string query = "SELECT one, two, three FROM table WHERE id = " + TextBox1.Text;
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
int num = sda.Fill(ds);
if (num > 0)
{
GridView1.Visible = true;
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
if (num == 0)
{
GridView1.Visible = false;
}
else
{
BindGrid();
}
}
}

Try using the RowDataBound event. For this to work, the drop-down-lists must already be populated with values, and in the event, the SelectedValue will be assigned.
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// this assumes the drop-down-list columns are the first, second, and third columns (ordinal positions 0, 1, and 2)
DropDownList ddl1, ddl2, ddl3;
ddl1 = (DropDownList)e.Row.Cells[0].Controls[0];
ddl2 = (DropDownList)e.Row.Cells[1].Controls[0];
ddl3 = (DropDownList)e.Row.Cells[2].Controls[0];
DataRow currentRow = (DataRow)e.Row.DataItem;
ddl1.SelectedValue = currentRow[0].ToString();
ddl2.SelectedValue = currentRow[1].ToString();
ddl3.SelectedValue = currentRow[2].ToString();
}
}

Related

selected index value in C# with combobox with database

I am new in c# and I have a question.
I want to select a value from a combobox and it should show in a label it's age.
What I do is this:
public void FillCombo()
{
SqlDataAdapter adap = new SqlDataAdapter("Select * from customers",con);
DataTable dt = new DataTable();
adap.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "id";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from customers where name=#name ", con);
cmd1.Parameters.AddWithValue("#name",comboBox1.SelectedItem));
int i= cmd1.ExecuteNonQuery();
if (i > 0)
{
SqlDataReader sqlrdr = cmd1.ExecuteReader();
while (sqlrdr.Read())
{
String age= sqlrdr["age"].ToString();
label1.Text = age;
}
}
else{
MessageBox.Show("no value");
}
con.Close();
}
It shows no value message , even if i have values in database. What can I do?
When you set the DataSource to a DataTable then every item in the combobox is a DataRowView. So you already have the info about the age of the current customer in the combobox. No need to make another call to the database.
You just need to use the SelectedItem property to retrieve the info about the age field or any other field present in the DataSource
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView rv = l.SelectedItem as DataRowView;
// For safety, always check for null.
// It is possible that SelectedIndexChanged
// will be called even when there is no selection in the combobox
if(rv != null)
{
label1.Text = rv["age"].ToString();
....
}
}
Try this to obtain index,value and selected name:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
int selectedValue = (int)cmb.SelectedValue;
ComboboxItem selectedName = (ComboboxItem)cmb.SelectedItem;
}

C# Check if any checkbox in datagridview is checked

When I check a checkbox in dataGridView, the checkbox that I've checked is automatically becoming false because I am refreshing my dataGridView every second. What I want to happen is to cancel the refreshing every second when a dataGridView checkbox is checked.
Here is my code:
private void UpdateVisitors_Load(object sender, EventArgs e)
{
//Realtime refresh
refresher.Interval = (1 * 1000); // 10 secs
refresher.Tick += new EventHandler(refresh);
refresher.Start();
}
private void refresh(object sender, EventArgs e)
{
refreshLocal();
}
UPDATE
Here is my refreshLocal code that I've been using to refresh my dataGridView
void refreshLocal()
{
dgvLocal.Rows.Clear();
connection.Close();
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "Select * from tbl_Registration ORDER BY [ID] DESC;";
SqlDataAdapter adap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
myID = dr["ID"].ToString();
category = dr["Category"].ToString();
repname = dr["Representative"].ToString();
if (dr["City/Province"].ToString() == "")
{
city = dr["Province"].ToString();
}
else
{
city = dr["City/Province"].ToString();
}
pax = dr["Pax"].ToString();
male = dr["Male"].ToString();
female = dr["Female"].ToString();
students = dr["Students"].ToString();
ar = dr["AR Users"].ToString();
date = dr["Date & Time Added"].ToString();
dgvLocal.Rows.Add(false, myID, category, repname, city, pax,students, ar, date);
}
connection.Close();
}
You need to bind to the event CellValueChanged of your DataGridView and inside the handler, stop your timer depending on the value of your checkbox.
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
if (dataGridView.Columns[e.ColumnIndex].Name == "MyCheckBoxCellName" && dataGridView.Columns[e.ColumnIndex].Value) {
// Disable your Timer
refresher.Enabled = false;
}
}

Get value of the third column in a table in selectedindex changed event of dropdown list in asp.net

This is my code to display table value to a DropDownList.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString))
{
con.Open();
string str="SELECT ItemOne,ItemTwo,ItemThree FROM tableItem";
using (SqlCommand cmd = new SqlCommand(str, con))
{
SqlDataAdapter dA=new SqlDataAdapter(cmd);
dA.Fill(dT);
DropDownList1.DataSource = dT;
DropDownList1.DataValueField = "ItemTwo";
DropDownList1.DataTextField = "ItemOne";
DropDownList1.DataBind();
}
This is to display the selected value of DropDownList to a TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = //Get the value of ItemThree here
}
My problem is: How will I display the column value of ItemThree in another TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropDownList1.Items[2].ToString(); // 2 is your index
}
Another way of doing this
var connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
var sql = "SELECT ItemOne, ItemTwo, ItemThree FROM tableItem";
using (var table = new DataTable) {
using (var adapter = new SqlDataAdapter(sql, connectionString)
adapter.Fill(table);
foreach (DataRow dr in table.Rows)
DropDownList1.Items.Add(new ListItem(dr["ItemTwo"], dr["ItemTwo"]) {
Tag = dr["ItemThree"]
});
}
Then from the event handler
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropdownList1.SelectedItem.Tag.ToString();
}

Populate gridview from dropdown control (C#)

I worked on asp web page that have a dropdown of semester names, and according to the selected item from this dropdown a gridview of levels and courses will appear.
The problem is that grid view never change according to the drop down selection
So when i choose a semester name let's say "Fall", the gridview shows all semesters " Fall & Spring & Summer" with their levels and courses.
Here is my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvSemester.DataSource = GetData(string.Format("select COURSE_SEMESTER from COURSE GROUP BY COURSE_SEMESTER"));
gvSemester.DataBind();
}
}
private static DataTable GetData(string query)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = query;
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void Show_Hide_LevelsGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlLevels").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string semesterId = gvSemester.DataKeys[row.RowIndex].Value.ToString();// semester
GridView gvLevel = row.FindControl("gvLevel") as GridView;
BindLevels(semesterId, gvLevel);
}
else
{
row.FindControl("pnlLevels").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindLevels(string semesterId, GridView gvLevel)
{
gvLevel.ToolTip = semesterId;
gvLevel.DataSource = GetData(string.Format("SELECT COURSE_LEVEL from COURSE where COURSE_SEMESTER= '" + semesterId + "' GROUP BY COURSE_LEVEL ORDER BY COURSE_LEVEL")); //was COURSE_SEMESTER=Check it shows the selected semester levels for all
gvLevel.DataBind();
}
protected void Show_Hide_CoursesGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlCourses").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string levelId = (row.NamingContainer as GridView).DataKeys[row.RowIndex].Value.ToString();//level
GridView gvCourse = row.FindControl("gvCourse") as GridView;//..
BindCourses(levelId, gvCourse);//..
}
else
{
row.FindControl("pnlCourses").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindCourses(string levelId, GridView gvCourse)
{
gvCourse.ToolTip = levelId;
gvCourse.DataSource = GetData(string.Format("select * from COURSE where COURSE_LEVEL='{0}'", levelId));
gvCourse.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You can set your dropdown list AutoPostBack = True.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
BindLevels();
}
fill your gridview with dropdown SelectedIndexChanged event and apply where condition in your SQL query.
Add Update Panel for the "levels and courses" grid.
At the dropdown Change event , you update the grid.
UpdatePanelId.Update();

how to bind ASP.Net DropDownList control in EditItemTemplate of GridView on edit(imagebutton)click [duplicate]

This question already has answers here:
Binding dropdownlist inside gridview edititemtemplate
(5 answers)
Closed 1 year ago.
I have requirement to bind ASP.Net DropDownList control in EditItemTemplate of GridView.
I have a edit imagebutton with commandname="Edit"also dropdown needs to be binded from different table(directory) and not the table through which grid is binded(details).
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit && GridView1.EditIndex == e.Row.RowIndex)
{
DropDownList DStatusEdit = (DropDownList)e.Row.FindControl("DStatusEdit");
string query = "select distinct status from directory";
SqlCommand cmd = new SqlCommand(query);
DStatusEdit.DataSource = GetData(cmd);
DStatusEdit.DataTextField = "status";
DStatusEdit.DataValueField = "status"; DStatusEdit.DataBind();
DataStatusEdit.DataBind();
}
the page is running but when i click edit image button the dropdwn shows but no data in dropdown binded it is empty.
My gridview is inside update panel.
How can i achieve this?
Should dropdownlist in my case be binded inside rowcommand but how?
protected void gv_RowDataBound(object sender, GridViewEditEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList DStatusEdit= (DropDownList)e.Row.FindControl("DStatusEdit");
DataTable dt = con.GetData("select distinct status from directory");
DStatusEdit.DataSource = dt;
DStatusEdit.DataTextField = "status";
DStatusEdit.DataValueField = "status";
DStatusEdit.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
DStatusEdit.SelectedValue = dr["columnname"].ToString();
}
}
}
}
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex;
gridviewBind();// your gridview binding function
}
Your forgot to bind the dropdown list
DStatusEdit.DataBind();
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT GatePassNo,PurposeOfVisit FROM VisitorList"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
DropDownList ddlpurposeofvisit = (DropDownList)e.Row.FindControl("ddlpurposeofvisit");
ddlpurposeofvisit.DataSource = cmd.ExecuteReader();
ddlpurposeofvisit.DataTextField = "PurposeOfVisit";
ddlpurposeofvisit.DataValueField = "GatePassNo";
ddlpurposeofvisit.DataBind();
con.Close();
}
}
}
I think this is helpful
private void bind_gridview_with_dropdownlist()
{
DataSet ds = edtcoursedal.Loaddropdown();
foreach (GridViewRow grdRow in GridView1.Rows)
{
DropDownList bind_dropdownlist = (DropDownList)(GridView1.FooterRow.Cells[3].FindControl("drplmaincourse"));
bind_dropdownlist.DataSource = ds;
bind_dropdownlist.DataTextField = "C_name";
bind_dropdownlist.DataValueField = "MId";
bind_dropdownlist.DataBind();
}
bind_dropdownlist.Items.Insert(0,new ListItem("Select","0"));
}

Categories