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();
Related
Currently, there is 2 values in my DropDownList which is viewProduct and editProduct. So when the user selects one of the value, it will direct user to the particular function in ASP.NET. I have tried OnSelectedIndexChanged, but it seems like not working on the dynamic DropDownList.
Here is my code:
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
e.Row.Cells[5].Controls.Add(ddlAction);
if(ddlAction.SelectedValue == "editProduct")
{
editProduct();
}
else if(ddlAction.SelectedValue == "viewProduct")
{
retrieveProduct();
}
Any idea how to solve it without using JavaScript?
My entire code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private void BindGridView()
{
MySqlConnection conn = new MySqlConnection(sqlConn);
string sql = "SELECT prodID, prodName, stockLevel, reorderLevel, unitPrice from Product";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
productList.DataSource = dt;
productList.DataBind();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell tc = new TableCell();
DropDownList ddlAction = new DropDownList();
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "Prod ID";
e.Row.Cells[1].Text = "Product Name";
e.Row.Cells[2].Text = "Qty";
e.Row.Cells[3].Text = "Reorder Level";
e.Row.Cells[4].Text = "Price (RM)";
e.Row.Controls.Add(tc);
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
var qty = Int16.Parse(e.Row.Cells[2].Text);
var reorder = Int16.Parse(e.Row.Cells[3].Text);
if (qty <= reorder)
{
e.Row.Cells[2].CssClass = "redCell";
e.Row.Cells[3].CssClass = "redCell";
}
e.Row.Controls.Add(tc);
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
e.Row.Cells[5].Controls.Add(ddlAction);
ddlAction.SelectedIndexChanged += DDLAction_OnSelectedIndexChanged;
if (ddlAction.SelectedValue == "editProduct")
{
editProduct();
}
else if (ddlAction.SelectedValue == "viewProduct")
{
retrieveProduct();
}
}
}
You need to declare an event handler then assign it to the control before adding the control to the page.
Here is an example :
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
CreateControl();
}
}
protected void CreateControl()
{
var ddlAction = new DropDownList();
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
ddlAction.SelectedIndexChanged += DDLAction_OnSelectedIndexChanged;
e.Row.Cells[5].Controls.Add(ddlAction);
}
protected void DDLAction_OnSelectedIndexChanged(object sender, EventArgs e)
{
var action = (DropDownList) sender;
var choice = action.SelectedValue?.Trim();
string script = null;
switch (choice)
{
case "viewProduct":
script = "alert('View page!');";
break;
case "editProduct":
script = "alert('Edit page!');";
break;
default:
script = "alert('Unmatched Value!')";
break;
}
ScriptManager.RegisterStartupScript(this , typeof(_Default) , "TestJS" , $"<script>{script}</script>" , false);
}
use ScriptManager.RegisterStartupScript when you want to work with JS scripts. Response.Write will not parse script blocks as an executable blocks. It will throw a parse error though (you could check the browser console.
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();
}
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();
}
}
I have a repeater and I used label for display and a hidden text box which holds the same value. Now I want to enable the text box so that the user can edit inputs in the table/repeater. Can anyone help me? below is my code
public void FillTable()
{
DataTable table = new DataTable();
using (MySqlConnection conn = Functions.GetConnection())
{
string sql = "SELECT FirstName, LastName from tbluser LIMIT 15";
using (MySqlCommand cmd = new MySqlCommand(sql, conn))
{
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(table);
conn.Close();
}
}
asd.DataSource = table;
asd.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
asd.Visible = true;
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
RepeaterItem item = e.Item;
Literal lblname = (Literal)item.FindControl("Label2");
TextBox txtbox = (TextBox)item.FindControl("Label3");
if (e.CommandName == "EDIT")
{
lblname.Visible = false;
txtbox.Visible = true;
You are not getting the textbox but the label twice:
TextBox txtbox = (TextBox)item.FindControl("Label3");
We want to attach a combo box into a cell of data grid view. Now it works with mouse click. but for faster moving of form we need it to work using keyboard.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void CreateGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("EmpName", typeof(string));//0
dt.Columns.Add("EmpID", typeof(int));//1
dt.Columns.Add("PhoneNo", typeof(string));//2
dt.Columns.Add("Address", typeof(string));//3
dt.Columns.Add("Email", typeof(string));//4
dataGridView1.DataSource = dt;
dataGridView1.Controls.Add(comboBox1); // Add System.Windows.Form.ComboBox in Datagridview
}
private void Form1_Load(object sender, EventArgs e)
{
CreateGrid();
fillRecords(1);
}
string SQL;
void fillRecords(int QueryNo)
{
SqlConnection con = new SqlConnection(#"Data Source=APPLE-PC\RNS;Initial Catalog=DemoDatabase;User ID=sa;Password=rns11");
con.Open();
if (QueryNo==1)
{
SQL = "Select EmpName,EmpID from EmployeeMaster";
}
else if (QueryNo==2)
{
SQL = "Select PhoneNo,Address from EmployeeMaster where EmpID=" + comboBox1.SelectedValue.ToString();
}
SqlDataAdapter da = new SqlDataAdapter(SQL, con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if (QueryNo == 1)
{
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "EmpName";
comboBox1.ValueMember = "EmpID";
}
else if (QueryNo == 2)
{
dataGridView1.CurrentRow.Cells[1].Value = comboBox1.SelectedValue.ToString();
dataGridView1.CurrentRow.Cells[0].Value = comboBox1.Text;
DataRow dr=dt.Rows[0];
dataGridView1.CurrentRow.Cells[2].Value = dr["PhoneNo"];
dataGridView1.CurrentRow.Cells[3].Value = dr["Address"];
}
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
//Visible Location on Current Cell
if (dataGridView1.CurrentCell.ColumnIndex==0)
{
comboBox1.Visible = true;
comboBox1.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Size = dataGridView1.CurrentCell.Size;
}
}
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
comboBox1.Visible = false;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue.ToString()!="System.Data.DataRowView")
{
fillRecords(2);
}
}
}
this solution is given by Sinisa Hajnal.
It should work using keyboard, but usually need to press F2 first to enter edit mode. I can solve this by handling CellEnter event and opening edit mode for combobox and setting focus to it inside.
`
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex==0)
{
comboBox1.Visible = true;
comboBox1.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Size = dataGridView1.CurrentCell.Size;
comboBox1_SelectedIndexChanged(null, null);
comboBox1.Focus();//focus on Combobox
}
}
`