Dropdownlist does not update after adding update panel - c#

I have multiple dropdownlist box all querying the same column, same table and from the same database. For example under memberID column i have the following IDs.
12345
23456
34567
And i have 3 different dropdownlist box as shown below
<asp:DropDownList ID="memberID3" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid3_SelectedIndexChanged" >
</asp:DropDownList>
<asp:DropDownList ID="memberID1" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID2" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid2_SelectedIndexChanged">
</asp:DropDownList>
I added update panel between the dropdownlist so as to allow my dropdownlist to refresh upon any updates/selections.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
For instance, when memberID1 selected 12345, the other 2 dropdownlist (memberID2 and 3) will not display the ID 12345. Vice versa, when memberID1 select the default value of the dropdownlist, the ID reappears in the other 2 dropdownlistbox. I have added a default value for all of the DDL.
memeberID(number).Items.Insert(0, new ListItem(" Please select a Member ID", ""));
memeberID(number).SelectedIndex = 0;
If i have not mistaken the property of update panel, isn't that able to make this function work?
here is the binding code as requested.
protected void ddllocation_SelectedIndexChanged(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
memberID1.Items.Clear();
memberID1.DataSource = ds2;
memberID1.DataTextField = "memberID";
memberID1.DataValueField = "memberID";
memberID1.DataBind();
memberID1.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID1.SelectedIndex = 0;
memberID2.Items.Clear();
memberID2.DataSource = ds2;
memberID2.DataTextField = "memberID";
memberID2.DataValueField = "memberID";
memberID2.DataBind();
memberID2.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID2.SelectedIndex = 0;
memberID3.Items.Clear();
memberID3.DataSource = ds2;
memberID3.DataTextField = "memberID";
memberID3.DataValueField = "memberID";
memberID3.DataBind();
memberID3.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID3.SelectedIndex = 0;
}
UPDATE
For now i'm able to allow my other ddl to re-bind and cache the selected value in the other dropdownlist when the default value is selected. However, when i select other ID, the ID are being removed and it wont re-bind the other ddl.
protected void FillddlLocations()
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.Visible = false;
ddlpid2.Visible = false;
ddlpid3.Visible = false;
ddlpid4.Visible = false;
ddlpid5.Visible = false;
}
protected void FillDropdown(DropDownList ddl)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
ddl.Items.Clear();
ddl.DataSource = ds2;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Police ID", ""));
ddl.SelectedIndex = 0;
}
}
}
protected void ddlpid1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid1.SelectedIndex > 0)
{
Session["pid1"] = ddlpid1.SelectedValue;
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else
if (ddlpid1.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid2_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid2.SelectedIndex > 0)
{
Session["pid2"] = ddlpid2.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid2.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid3_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid3.SelectedIndex > 0)
{
Session["pid3"] = ddlpid3.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid3.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid4_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid4.SelectedIndex > 0)
{
Session["pid4"] = ddlpid4.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid4.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid5_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid5.SelectedIndex > 0)
{
Session["pid5"] = ddlpid5.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
}
else if (ddlpid5.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
}
}

First of all, I would set the AutoPostBack property for dropdowns to true in my markup:
<asp:DropDownList ID="memberID1" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID2" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid2_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID3" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid3_SelectedIndexChanged" >
</asp:DropDownList>
Update: We can store selected values in view state and retrieve after repopulating the dropdownlists like below:
public partial class WebForm2 : System.Web.UI.Page
{
bool bFlag = true;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillddlLocations();
}
}
//Properties to store selected value in ViewState
protected string MemberID1Selection
{
get
{
if (ViewState["MemberID1Selection"] != null)
return ViewState["MemberID1Selection"].ToString();
return "";
}
set { ViewState["MemberID1Selection"] = value; }
}
protected string MemberID2Selection
{
get
{
if (ViewState["MemberID2Selection"] != null)
return ViewState["MemberID2Selection"].ToString();
return "";
}
set { ViewState["MemberID2Selection"] = value; }
}
protected string MemberID3Selection
{
get
{
if (ViewState["MemberID3Selection"] != null)
return ViewState["MemberID3Selection"].ToString();
return "";
}
set { ViewState["MemberID3Selection"] = value; }
}
protected void FillddlLocations()
{
FillDropdown(memberID1);
FillDropdown(memberID2);
FillDropdown(memberID3);
memberID1.Visible = true;
memberID2.Visible = true;
memberID3.Visible = true;
}
protected void FillDropdown(DropDownList ddl)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
ddl.Items.Clear();
ddl.DataSource = ds2;
ddl.DataTextField = "memberID";
ddl.DataValueField = "memberID";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please select a Member ID", ""));
ddl.SelectedIndex = 0;
}
}
}
protected void IndexChanged(DropDownList ddlChanged, DropDownList ddlToFilter1, DropDownList ddlToFilter2)
{
string removeValue1 = ddlChanged == memberID1 ? MemberID1Selection : (ddlChanged == memberID2 ? MemberID2Selection : MemberID3Selection);
string selValue2 = ddlChanged == memberID1 ? MemberID2Selection : (ddlChanged == memberID2 ? MemberID1Selection : MemberID1Selection);
string selValue3 = ddlChanged == memberID1 ? MemberID3Selection : (ddlChanged == memberID2 ? MemberID3Selection : MemberID2Selection);
bFlag = false;//Prevent fireing the code again while changing the index
if (removeValue1 != "")
{
ListItem item1 = ddlToFilter1.Items.FindByValue(removeValue1);
ddlToFilter1.Items.Remove(item1);
ListItem item2 = ddlToFilter2.Items.FindByValue(removeValue1);
ddlToFilter2.Items.Remove(item2);
}
if (selValue3 != "")
{
ListItem item3 = ddlToFilter1.Items.FindByValue(selValue3);
ddlToFilter1.Items.Remove(item3);
}
if (selValue2 != "")
{
ListItem item4 = ddlToFilter2.Items.FindByValue(selValue2);
ddlToFilter2.Items.Remove(item4);
}
bFlag = false;
ddlToFilter1.SelectedIndex = ddlToFilter1.Items.IndexOf(ddlToFilter1.Items.FindByValue(selValue2));
ddlToFilter2.SelectedIndex = ddlToFilter2.Items.IndexOf(ddlToFilter2.Items.FindByValue(selValue3));
}
protected void ddlpid1_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID1Selection = memberID1.SelectedValue;
if (bFlag)
{
FillDropdown(memberID2);
FillDropdown(memberID3);
IndexChanged(memberID1, memberID2, memberID3);
}
}
protected void ddlpid2_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID2Selection = memberID2.SelectedValue;
if (bFlag)
{
FillDropdown(memberID1);
FillDropdown(memberID3);
IndexChanged(memberID2, memberID1, memberID3);
}
}
protected void ddlpid3_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID3Selection = memberID3.SelectedValue;
if (bFlag)
{
FillDropdown(memberID1);
FillDropdown(memberID2);
IndexChanged(memberID3, memberID1, memberID2);
}
}
}
I have tested the code and it is working for me. Hope it helps!

Related

How to do OnClick on selected item in "dynamic" ASP.NET DropDownList without using JavaScript

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.

How to disable click of a column from a DataGridView?

I have a DataGridView on WindowsForm where I'm passing data from my database. The purpose of this DataGridView is to enable to user to click on a value and modify it. However, I don't want the user to leave the value blank, add words, only numbers.. and of course not change the Id, which is the primary key of my table.
I'm trying to achieve this by disabling the column which host the id of the table, however I don't know how to tell that column to disable editing.
Here is my code:
public partial class eraseGrade : Form
{
Conexion con;
String rut;
DataTable dt;
SqlDataAdapter sda;
SqlCommandBuilder scb;
public eraseGrade()
{
InitializeComponent();
cbxAsig.Enabled = false;
cbxAsig.Enabled = false;
btnNotas.Enabled = false;
btnBorra.Enabled = false;
}
private void btnBuscar_Click_1(object sender, EventArgs e)
{
Conexion con = Conexion.saberEstado();
rut = txtRut.Text.Trim();
if (validarTXTVacios(txtRut))
{
MessageBox.Show("Add a Rut, please");
}
else
{
Alumno a = new Alumno(rut);
a.buscar(a);
cbxAsig.Items.Clear();
if (a.Nombre != null)
{
lblNombre.Text = a.Nombre + " " + a.Apellido;
cbxAsig.Enabled = true;
AsignaturaAlumno b = new AsignaturaAlumno();
List<AsignaturaAlumno> l = b.buscarTodosByAlumno(rut);
List<String> codigosAsig = new List<string>();
if (l.Count != 0)
{
for (int i = 0; i < l.Count(); i++)
{
codigosAsig.Add(l.ElementAt(i).Cod_asig.ToString());
}
Asignatura asigT = new Asignatura();
List<Asignatura> asig = new List<Asignatura>();
for (int i = 0; i < codigosAsig.Count(); i++)
{
asig.Add(asigT.buscarbyCod(codigosAsig.ElementAt(i).ToString()));
}
for (int i = 0; i < asig.Count(); i++)
{
cbxAsig.Items.Add(asig.ElementAt(i).CodAsignatura);
}
cbxAsig.Enabled = true;
btnNotas.Enabled = true;
}
}
else
{
lblNombre.Text = "";
MessageBox.Show("Alumno no encontrado");
lblAsig.Text = "";
cbxAsig.Enabled = false;
btnNotas.Enabled = false;
btnBorra.Enabled = false;
}
}
}
private void cbxAsig_SelectedIndexChanged(object sender, EventArgs e)
{
Conexion con = Conexion.saberEstado();
Asignatura asignatura = new Asignatura();
Asignatura l = asignatura.buscarbyCod(cbxAsig.SelectedItem.ToString());
lblAsig.Text = l.Nombre + " (" + l.IdSeccion + ")";
}
Here is the code that obtains data from the database and inserts it into the DataGridView.
private void btnNotas_Click(object sender, EventArgs e)
{
Conexion con = Conexion.saberEstado();
if (cbxAsig.SelectedItem != null)
{
String codigo = cbxAsig.SelectedItem.ToString();
sda = new SqlDataAdapter(#"SELECT id, num_eval AS Evaluacion, porcentaje AS Porcentaje, nota AS Nota FROM registro WHERE rut = #rut AND cod_asig = #cod_asig", con.Con);
sda.SelectCommand.Parameters.AddWithValue("#rut", rut);
sda.SelectCommand.Parameters.AddWithValue("#cod_asig", codigo);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
btnBorra.Enabled = true;
}
else
{
MessageBox.Show("Seleccione una asignatura");
}
}
public Boolean validarTXTVacios(TextBox r)
{
if (txtRut.Text.Equals(""))
{
return true;
}
return false;
}
Here is the button that updates the table with the new data from the columns. It doesn't respect primary keys or data types.
private void btnBorra_Click(object sender, EventArgs e)
{
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
}
}
}
Just set that column's ReadOnly to true like this:
dataGridView1.Columns[0].ReadOnly = true;
You should change 0 to the id's column index.
EDIT: To validate a column to be for example int you could do like this:
dataGridView1.Columns[0].ReadOnly = true;
dataGridView1.AllowUserToAddRows = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int x;
if (int.TryParse(row.Cells[1].Value.ToString(), out x))
{
MessageBox.Show("Valid");
}
}
You can achieve this by setting Row.Cells[cellIndex].Enabled = false; during GridView RowDataBound event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[cellIndex].Enabled = false;
}
}
Alter cellIndex to your actual id cell index.

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

selection through drop down list

How can i execute a SELECT query from a drop down list. I have a drop down that contains diploma degrees and in my database i have a table called Alumni(Aid,...,Diploma) and a table called Diploma which contains (Did,Diploma) and we have 5 diplomas manually inserted (brevet,bacc2,bachelor,master,doctoral). What i want is to select a diploma from the drop down list so it can end up in Alumni table after i confirm or submit. Here's my code.
Form.aspx:
<form id="form" runat="server" method="post">
<div>
<table class="style1">
<tr>
<td>Diploma:</td>
<td>
<asp:DropDownList ID="Diploma" runat="server" AppendDataBoundItems="true" Width="160px">
<asp:ListItem Text="Select Degree" Value="Select Degree"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
<center>
<asp:Button ID="Button1" runat="server" Text="Next" OnClick="Button1_Click" Width="85px" />
</center>
</form>
Form.aspx.cs:
protected void Button_Click(object sender, EventArgs e)
{
Session["diploma"] = Diploma.SelectedValue;
if (Status.Text == "1")
{
Response.Redirect("C2.aspx");
}
else
{
Response.Redirect("C1.aspx");
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["diploma"] != null &&)
{
Diploma.SelectedValue = Session["diploma"].ToString();
}
}
}
C1.aspx.cs:
if (!Page.IsPostBack)
{
if (Session["pname"] != null && Session["plastname"] != null && Session["pos"] != null &&
Session["children"] != null && Session["schoolofchildren"] != null &&
Session["schoolofchildren1"] != null && Session["schoolofchildren2"] != null)
{
PName.Text = Session["pname"].ToString();
PLastName.Text = Session["plastname"].ToString();
OldStudent.Text = Session["pos"].ToString();
Children.Text = Session["children"].ToString();
SchoolOfChildren.Text = Session["schoolofchildren"].ToString();
SchoolOfChildren1.Text = Session["schoolofchildren1"].ToString();
SchoolOfChildren2.Text = Session["schoolofchildren2"].ToString();
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Session["pname"] = PName.Text;
Session["plastname"] = PLastName.Text;
Session["pos"] = OldStudent.Text;
Session["children"] = Children.Text;
Session["schoolofchildren"] = SchoolOfChildren.Text;
Session["schoolofchildren1"] = SchoolOfChildren1.Text;
Session["schoolofchildren2"] = SchoolOfChildren2.Text;
Response.Redirect("Form.aspx");
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["pname"] = PName.Text;
Session["plastname"] = PLastName.Text;
Session["pos"] = OldStudent.Text;
Session["children"] = Children.Text;
Session["schoolofchildren"] = SchoolOfChildren.Text;
Session["schoolofchildren1"] = SchoolOfChildren1.Text;
Session["schoolofchildren2"] = SchoolOfChildren2.Text;
Response.Redirect("C2.aspx");
}
protected void Button4_Click(object sender, EventArgs e)
{
try
{
ExecuteInsert1(Session["diploma"].ToString());
ExecuteInsert2(PName.Text, PLastName.Text, OldStudent.SelectedValue, Children.SelectedValue, SchoolOfChildren.Text, SchoolOfChildren1.Text,
SchoolOfChildren2.Text);
Response.Write("Successfully Added!");
ClearControls(Page);
Session.Clear();
}
catch{}
}
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["Champville1ConnectionString"].ConnectionString;
}
public static void ClearControls(Control Parent)
{
if (Parent is TextBox)
{ (Parent as TextBox).Text = string.Empty; }
else
{
foreach (Control c in Parent.Controls) ClearControls(c);
}
}
private void ExecuteInsert1(string diploma)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO Alumni (Diploma) VALUES " + " (#Diploma)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("#Diploma", SqlDbType.NVarChar, 50);
param[0].Value = diploma;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
private void ExecuteInsert2(...){}

Radio button list selected value not persistent in asp.net

I have two dynamically populated radio button lists. The first one gets populated on a button click, the other one on the change event of the first radio button list. The problem is only with the second list. The issue is that I am not able to retrieve the changed value of the second radio button list in the InsertButton_Click method(marked by **). It always returns the default index value i.e 0. I don't have anything in page_load event. I read quite a few similar questions but none seem to help. Please guide. Below is the asp and c# code for the same:
ASP:
<asp:Button id="SaveButton"
Text="Save"
runat="server" onclick="SaveButton_Click">
</asp:Button>
<asp:Button id="VisualiseButton"
Text="Visualise"
runat="server" onclick="VisualiseButton_Click">
</asp:Button>
<!--<hr />-->
<asp:RadioButtonList id="RadioButtonList2" runat="server" Visible="false"
onselectedindexchanged="RadioButtonList2_SelectedIndexChanged" ></asp:RadioButtonList>
<asp:RadioButtonList id="RadioButtonList1" runat="server" Visible="false" ></asp:RadioButtonList>
<asp:Button id="SaveToDBButton"
Text="Insert"
runat="server" Visible="false" onclick="InsertButton_Click">
C#:
protected void SaveButton_Click(object sender, EventArgs e)
{
String selQuery = "SELECT id, name FROM categories";
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(selQuery, con);
DataTable dt = new DataTable();
da.Fill(dt);
RadioButtonList2.DataSource = dt;
RadioButtonList2.DataTextField = "name";
RadioButtonList2.DataValueField = "id";
RadioButtonList2.DataBind();
RadioButtonList2.RepeatColumns = 3;
RadioButtonList2.AutoPostBack = true;
RadioButtonList2.Visible = true;
}
catch (SqlException ex)
{
}
finally
{
if (con != null)
{
con.Close();
}
}
}
protected void RadioButtonList2_SelectedIndexChanged(object sender, EventArgs e)
{
String catId = RadioButtonList2.SelectedValue;
SqlCommand cmdselect = new SqlCommand("SELECT DISTINCT categoryId, linkTablesCategories.tableName, tableDescription FROM linkTablesCategories, tableDescriptions where linkTablesCategories.tableName = tableDescriptions.tableName and categoryId ='" + catId + "'");
RadioButtonList1.Items.Clear();
try
{
con.Open();
cmdselect.Connection = con;
SqlDataReader dar = cmdselect.ExecuteReader();
if (dar.HasRows)
{
while (dar.Read())
{
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
li.Attributes.Add("title", dar["tableDescription"].ToString());
RadioButtonList1.Items.Add(li);
}
}
RadioButtonList1.Visible = true;
SaveToDBButton.Visible = true;
}
catch (SqlException ex)
{
//lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
}
protected void InsertButton_Click(object sender, EventArgs e)
{
String tableId="";
**tableId = RadioButtonList1.SelectedItem.Text;**
String path = Server.MapPath("~/");
string filepath = path + Session["filepath"].ToString();
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = tableId;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
it was with the line:
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
The categoryId was a constant value and thus the issue, again my bad.
Thanks

Categories