I'm trying to display textboxes based on the checkboxlist items that the user has selected. I have 15 items in my checkboxlist with a textbox which corresponds to each when selected. I've made this code but I am unsure how to proceed. My goal is to look through the items in my checkboxlist and whenever it finds a selected item, it will make visible the div which displays the textbox. The textbox will have almost the same name as it's check box list equivalent. My problem is Im not quite sure how to take that value and making it so that it looks for the textbox control with the same name and display.
This is what I have so far:
{
foreach(ListItem item in cblReasonSeekingServices.Items)
{
if (item.Selected == true)
{
string strControlName = item.Value;
string strSpaceRemoved = Regex.Replace(strControlName, " ", "");
((TextBox)FindControl("pnl" + strSpaceRemoved)).Visible = true;
}
}
}
EDIT: I'm able to run the code now without any error messages however, the textbox control does not display. Am I missing anything?
foreach(ListItem item in cblReasonSeekingServices.Items)
{
if (item.Selected == true)
{
string strControlName = item.Value;
string strSpaceRemoved = Regex.Replace(strControlName, " ", "");
string test = ("tb" + strSpaceRemoved);
TextBox tBox = this.Master.FindControl("body").FindControl("tbBehavioralDifficulties") as TextBox;
tBox.Visible = true;
}
Hum, ok, say we have 5 text box, and then
So, say this:
<div style="float:left;width:20%">
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
</div>
<div style="float:left;width:20%">
<asp:TextBox ID="TextBox1" runat="server" Text="Text1"> </asp:TextBox> <br />
<asp:TextBox ID="TextBox2" runat="server" Text="Text2"> </asp:TextBox> <br />
<asp:TextBox ID="TextBox3" runat="server" Text="Text3"> </asp:TextBox> <br />
<asp:TextBox ID="TextBox4" runat="server" Text="Text4"> </asp:TextBox> <br />
<asp:TextBox ID="TextBox5" runat="server" Text="Text5"> </asp:TextBox> <br />
</div>
<div style="clear:both;height:20px">
</div>
<asp:Button ID="Button1" runat="server" Text="Show selected" OnClick="Button1_Click" />
And code behind is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 1; i <= 5; i++)
{
ListItem OneItem = new ListItem("Choice #" + i, i.ToString());
CheckBoxList1.Items.Add(OneItem);
// hide the text box
string sTbox = "TextBox" + i;
TextBox Tbox = Page.FindControl(sTbox) as TextBox;
Tbox.Visible = false;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (ListItem Choice in CheckBoxList1.Items)
{
string sTbox = "TextBox" + Choice.Value;
TextBox Tbox = Page.FindControl(sTbox) as TextBox;
Tbox.Visible = Choice.Selected;
}
}
So, we get this then - select a few check box, hit button:
I have a table which I need to populate with some results, based on what I select. While the table itself is already present, the rows need to be generated dynamically. I have found posts which help me create the rows and preserve them upon a page refresh, but my problem now is that when I try to repopulate the table upon a refresh, the table itself is seen as null.
This here is the front end, where given the selected items and if generate MZA is unchecked, then a list of excels needs to be made in the table.
<div class="jumbotron" Style="width:1200px; margin-top:-50px">
<div class="panou_raport1">
<p class="lead2">Selectați DRDP-ul :</p>
<asp:DropDownList ID="ddl_select_drdp" runat="server" ToolTip="Selectați DRDP" OnSelectedIndexChanged="Schimba_DRDP" AutoPostBack="True" CssClass="DRDP1"></asp:DropDownList>
<p class="lead2">Selectați judetul:</p>
<asp:DropDownList ID="ddl_select_judet" runat="server" ToolTip="Selectați judet" OnSelectedIndexChanged="Schimba_Judet" AutoPostBack="True" CssClass="DRDP1"></asp:DropDownList>
<p class="lead2">Selectați categorie drum :</p>
<asp:CheckBoxList ID="chbx_catDrum" runat="server" ToolTip="Selectați categorie" OnSelectedIndexChanged="Schimba_Categorie" RepeatDirection="Horizontal" AutoPostBack="true" CssClass="DRDP1" Width="75%">
<asp:ListItem>DN</asp:ListItem>
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>VO</asp:ListItem>
<asp:ListItem>DJ</asp:ListItem>
<asp:ListItem>DC</asp:ListItem>
</asp:CheckBoxList>
<p class="lead2">Selectați post:</p>
<asp:DropDownList ID="ddl_select_post" runat="server" ToolTip="Selectați post" OnSelectedIndexChanged="Schimba_Post" AutoPostBack="True" CssClass="DRDP1"></asp:DropDownList>
<p class="lead2">Selectați data:</p>
<asp:DropDownList ID="ddl_select_data" runat="server" ToolTip="Selectați data" AutoPostBack="True" CssClass="DRDP1"></asp:DropDownList>
<p class="lead2">MZA</p>
<asp:CheckBoxList ID="chbx_MZA" runat="server" ToolTip="Bifati MZA" OnSelectedIndexChanged="Verifica_MZA" RepeatDirection="Horizontal" AutoPostBack="true" CssClass="DRDP1" Width="75%">
<asp:ListItem Selected="True">Genereaza MZA</asp:ListItem>
</asp:CheckBoxList>
<div class="viabil_rap">
<asp:Button ID="btn_lista_excel" runat="server" OnClick="btn_genereaza_Click" text="Genereaza" CssClass="buton1" Visible="false" UseSubmitBehavior="False" Style="margin-top:40px"/>
</div>
<div class="mza_excel">
<asp:ImageButton ID="img_export_excel" ImageUrl="Content/images/excel.png" CssClass="img_excel" runat="server" OnClick="btn_MZA_Click" UseSubmitBehavior="False" />
</div>
<div class="excel_descarca">
<asp:Button ID="DownloadSelected" runat="server" OnClick="Descarca_Excel_Click" text="Descarca" CssClass="buton1" UseSubmitBehavior="false" Visible ="False" style="margin-top: 50px; margin-bottom: 20px"/>
</div>
</div>
<br/>
<div class="panou_raspuns1">
<div class="datagrid2" style="overflow-y: auto; overflow-x: auto;">
<asp:Table ID="tbl_excel_recensamant" runat="server" GridLines="Both" CssClass="Table1" Width="600px">
<asp:TableRow ID="row_excel_recensamant" runat="server" HorizontalAlign="Center">
<asp:TableCell runat="server" style="color:white; width:3%; background-color:#567bb7; font-size:16px;">Selectează</asp:TableCell>
<asp:TableCell runat="server" style="color:white; width:8%; background-color:#567bb7; font-size:16px;">Data inspectii</asp:TableCell>
</asp:TableRow>
</asp:Table>
</div>
</div>
</div>
This here is the backend. In here I try to recreate the generated rows (which are a checkbox with an excel download btn and a date) in the Page_PreInit. The function that creates the rows themselves is CreateCheckBox(), while btn_genereaza_Click() first creates the table with its rows, and gives each Checkbox an ID, which is stored in a list so I can then check which checkboxes have been checked. Problem is, when clicking the Download btn after the table with the results is first made, it empties the table values even if the checkboxes and excel btns are still displayed (like the checkbox ID), hence why I need the PreInit. But as it gets to that, in the CreateCheckBox() when called a second time, from within Page_PreInit, the table itself, which is defined in the front end, is null. What am I doing wrong?
List<string> ID_Checkbox = new List<string>();
List<string> ID_Checked = new List<string>();
List<string> Excel_list = new List<string>();
protected void Page_PreInit(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("ChBx")).ToList();
foreach (string key in keys)
{
string chbx_id = key.Replace("ctl00$MainContent$", string.Empty);
string img_id = key.Replace("ctl00$MainContent$ChBx", string.Empty);
CreateCheckBox(chbx_id, img_id);
}
}
protected void btn_genereaza_Click(object sender, EventArgs e)
{
//code that checks all selected options and runs a SELECT
SqlDataReader rd = cmd.ExecuteReader();
List<string> lista_genertate = new List<string>();
if (rd.HasRows)
{
string data_raport = "";
while (rd.Read())
{
data_raport = rd[rd.GetOrdinal("DataRaport")].ToString().Split(' ')[0];
string id_chbx = "ChBx" + data_raport;
lista_genertate.Add(id_chbx);
CreateCheckBox(id_chbx, data_raport);
}
DownloadSelected.Visible = true;
btn_lista_excel.Visible = false;
}
rd.Close();
conn.Close();
Session["lista_excel"] = lista_genertate;
}
private void CreateCheckBox(string id_chbx, string id_img)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
cell1.HorizontalAlign = HorizontalAlign.Center;
cell2.HorizontalAlign = HorizontalAlign.Center;
cell2.Text = id_img;
//Checkbox for each Excel
CheckBox cb = new CheckBox();
cb.Checked = false;
cb.ID = id_chbx;
cb.AutoPostBack = false;
cell1.Controls.Add(cb);
ID_Checkbox.Add(cb.ID);
cell1.Controls.Add(new LiteralControl(" "));
ImageButton img_select_excel = new ImageButton();
img_select_excel.ImageUrl = "Content/images/excel.png";
img_select_excel.Height = Unit.Pixel(30);
img_select_excel.Width = Unit.Pixel(30);
img_select_excel.ID = id_img;
img_select_excel.Click += new ImageClickEventHandler(btn_excel_Click);
cell1.Controls.Add(img_select_excel);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
tbl_excel_recensamant.Rows.Add(row); //HERE IS WHERE IT CRASHES, since it sees the table itself as null
tbl_excel_recensamant.HorizontalAlign = HorizontalAlign.Center;
}
I have a gridview that is being dynamically created based on the database. Some rows of the gridview have 2 DropDownLists, while others do not depending on the item in the row. The second DropDownList of the row is dynamically created based on the selection of the first DrowpDownMenu. Everything works as it should except, if you make the selections on the first row, then change the selection of the first DropDownList of the seccond row or click the update button, it will reset the second DropDownList of the first row. This is obviously due to PostBack. But I'd like to maintain the selection until all DropDownLists have been selected and I save the changes to the DB. Any help would be very appreciated.
My Gridview:
<asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True"
GridLines="Vertical" CellPadding="4" CssClass="table table-striped table-bordered"
OnRowDataBound="CartList_RowDataBound">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ID" SortExpression="ProductID" />
<asp:BoundField DataField="Product.ProductName" HeaderText="Name" />
<asp:BoundField DataField="Product.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text='<%# Eval("Quantity") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Size">
<ItemTemplate>
<asp:DropDownList ID="Sizeddl" runat="server" Font-Size="Medium"
AutoPostBack="true" ForeColor="Black" OnSelectedIndexChanged="Sizeddl_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Color">
<ItemTemplate>
<asp:DropDownList ID="ColorNameddl" runat="server"
Font-Size="Medium" ForeColor="Black">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Total">
<ItemTemplate>
<%#: String.Format("{0:c}", ((Convert.ToDouble( Eval("Quantity") )) * Convert.ToDouble(Eval("Product.UnitPrice"))))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove Item">
<ItemTemplate>
<asp:CheckBox ID="Remove" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div>
<p></p>
<strong>
<asp:Label ID="LabelSubtotal" runat="server" Text="SubTotal: "></asp:Label>
<asp:Label ID="lblSubtotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
<p></p>
<strong>
<asp:Label ID="LabelTax" runat="server" Text="Tax Total: "></asp:Label>
<asp:Label ID="lblTax" runat="server" EnableViewState="false"></asp:Label>
</strong>
<p></p>
<strong>
<asp:Label ID="LabelTotalText" runat="server" Text="Order Total: "></asp:Label>
<asp:Label ID="lblTotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
</div>
<br />
<table>
GridView Load:
DataTable rstSize = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
{
decimal cartTotal = 0;
cartTotal = usersShoppingCart.GetTotal();
if (cartTotal > 0)
{
// Display Total.
lblSubtotal.Text = String.Format("{0:c}", usersShoppingCart.GetSubtotal());
lblTax.Text = String.Format("{0:c}", usersShoppingCart.GetTax());
lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
}
else
{
lblSubtotal.Text = "";
lblTax.Text = "";
lblTotal.Text = "";
ShoppingCartTitle.InnerText = "Shopping Cart is Empty";
UpdateBtn.Visible = false;
CheckoutImageBtn.Visible = false;
}
if (!IsPostBack)
{
LoadGrid();
}
}
}
void LoadGrid()
{
// Load Cart Items.
using (ShoppingCartActions actions = new ShoppingCartActions())
{
var _db = new ProductContext();
string cartId = actions.GetCartId();
var cart = _db.ShoppingCartItems.Where(
c => c.CartId == cartId).ToList();
// Create DataTable for Colors
rstSize.Columns.Add("SizeName", typeof(string));
var row = rstSize.NewRow();
row["SizeName"] = "S";
row["SizeName"] = "M";
row["SizeName"] = "L";
row["SizeName"] = "XL";
row["SizeName"] = "2XL";
CartList.DataSource = cart;
CartList.DataBind();
// Hide DropDown Lists for rows that they are not needed for.
for (int i = 0; i < CartList.Rows.Count; i++)
{
DropDownList sizeDDL = CartList.Rows[i].FindControl("Sizeddl") as DropDownList;
DropDownList colorDDL = CartList.Rows[i].FindControl("ColorNameddl") as DropDownList;
IOrderedDictionary rowValues = new OrderedDictionary();
rowValues = GetValues(CartList.Rows[i]);
var _prodID = Convert.ToInt32(rowValues["ProductID"]);
var _prod = (from c in _db.Products
where c.ProductID == _prodID
select c.CategoryID).FirstOrDefault();
if (_prod != 1)
{
sizeDDL.Visible = false;
colorDDL.Visible = false;
}
}
}
}
My RowDataBound:
protected void CartList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem;
// Populate and select Color from DB.
DropDownList sizeDDL = (DropDownList)e.Row.FindControl("Sizeddl");
sizeDDL.DataSource = rstSize;
sizeDDL.DataBind();
sizeDDL.Items.Insert(0, new ListItem("Select Size", "0"));
sizeDDL.SelectedValue = gData["SizeName"].ToString();
// Load Color DDL
var _size = sizeDDL.SelectedItem.Text;
int _prod = Convert.ToInt32(e.Row.Cells[0].Text);
var _db = new ProductContext();
var qryColor = (from p in _db.ProductAttributes
join c in _db.Colors
on p.ColorID equals c.ColorID
where p.SizeName == _size & p.ProductID == _prod
select new { p.ColorID, c.ColorName }).Distinct().ToList();
DropDownList colorDDL = (DropDownList)e.Row.FindControl("ColorNameddl");
// Create DataTable for Colors
DataTable rstColor = new DataTable();
rstColor.Columns.Add("ColorID", typeof(int));
rstColor.Columns.Add("ColorName", typeof(string));
foreach(var item in qryColor)
{
var row = rstColor.NewRow();
row["ColorID"] = item.ColorID;
row["ColorName"] = item.ColorName;
rstColor.Rows.Add(row);
}
// Bind Color Drop Down List to DataTable.
colorDDL.DataSource = rstColor;
colorDDL.DataBind();
colorDDL.Items.Insert(0, new ListItem("Select Color", "0"));
colorDDL.SelectedValue = gData["ColorName"].ToString();
}
}
My SelectedIndexChanged
protected void Sizeddl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList sizeDDL = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)sizeDDL.NamingContainer;
string strSize = sizeDDL.SelectedItem.Text;
DropDownList colorDDL = (DropDownList)gRow.FindControl("ColorNameddl");
if (strSize != "Choose one")
{
using (ProductContext context = new ProductContext())
{
int _prodID = Convert.ToInt32(gRow.Cells[0].Text);
var _size = sizeDDL.SelectedItem.Text;
var qryColor = (from p in context.ProductAttributes
join c in context.Colors
on p.ColorID equals c.ColorID
where p.SizeName == _size & p.ProductID == _prodID
select new { p.ColorID, c.ColorName }).Distinct().ToList();
if (qryColor.Count > 0)
{
colorDDL.DataSource = qryColor;
colorDDL.DataTextField = "ColorName";
colorDDL.DataValueField = "ColorID";
colorDDL.DataBind();
colorDDL.Items.Insert(0, new ListItem("Select Color", "0"));
colorDDL.Enabled = true;
}
else
{
colorDDL.Items.Clear();
colorDDL.Items.Insert(0, new ListItem("No Colors Available", "0"));
colorDDL.Enabled = false;
}
}
}
}
if you make the selections on the first row
By "selections" are we to assume make changes - or select/change a value in the combo boxes, right?
I'd like to maintain the selection until all DropDownLists have been selected and I save the changes to the DB. Any help would be very appreciated.
A grid view will and should handle post backs on the page. After all, even outside of the GV, any old button or control can and will cause post-backs.
There is no reason that changes to ANY grid row by users, and that includes drop down lists (DDL) should matter. And operations on one row should not effect operations on other rows. The so called "view" state of the GV is automatic, and for the most part you should not have to worry.
So, it not at all clear why you posted the "add row", since all of this question centers on editing or making changes to the current row. (for us, say next week or when ever, we can look at or deal with the row created, but for now lets concentrate on the changes to a given row, and why for some reason you see effects in other rows - you should not be seeing this.
Tops on the list?
While controls - including a GV can and should handle post-backs without issue?
That is NOT the case if a post-back causes a re-bind of the grid. If that is to occur, then you going have issues.
So, tops on the list?
You left out how/when/where you are loading up the GV.
(the MOST important part!!!!).
Next up?
You do NOT want nor need to show the row PK id in the GV. These numbers not only mean nothing to the end user but it also a security risk - PK row numbers don't need to be displayed, and in fact do not even need to be included in the row markup. We again can leave that issue for another day, but you can (and should consider) using DataKeys for the row PK id operations. We assume no duplicate PK row id in the database, right? In other words, make sure you have a database row PK "id" in your data.
So, you can in the future, remove that ProductID. GV has a special feature for dealing with the PK row id - and we should be using that. (Datakeys)
Ok, now that we cleared up the above?
In the page load event, we need to load the GV, but ONLY on first page load - after that, we can't re-load the GV (bind again), else you WILL lose your changes, and edits to the GV.
Also, you might want to consider a save button at the bottom - to save all gv changes - in place of doing this row by row. (but, one thing at a time here).
So first up, the code to load the GV, should be in page load.
Next up, that code has to ONLY run the first time.
eg:
if (!IsPostBack)
{
code here to load GV
}
Next up? when the GV is loaded with that data, you need to setup the combo box and the cascade. And further more, this setup of each row should occur in the row data bound event.
So, your posted code does look ok, but we missing how/when you load the GV.
And we don't see your save button either. But at this point, I would share your code that loads up the GV - this all important information is missing here.
So edit your question - show how and when you load the grid up - that's missing.
Also, why the row created event being used here to setup a event? Just put the event stub and definition in the markup.
You are free to drop in a plane jane button, or DDL or whatever into the GV. And you should wire up the events like all other controls.
So, remove that row created event stub - it might be wiring up events for the wrong row - but it not required, and is a high risk adventure.
So, just do this:
So, for a button, or DDL in the GV? You can't double click on a button (to create a click event), and you can't display the property sheet to add events. But you can in markup just type in the event name, hit "=", and note how above intel-sense pops up a option to create the event. So, add the event that way. And after you select create new event, then you can flip over to code behind - you see the new event stub, and add your code to that stub. The GV uses internal information to wire up each row events - you may well be messing this up.
So, I would remove your row added - as we don't have details about that code and how/when you add a row, but 100% elimination of the row created event, and wiring up a click event will go a long way to elimination of any issues here - this would be especially the case if your row add event "copy's" controls - you might be copy the the DDL object when you do this, and that again will cause issues. In other words you may have the same object for two rows - changes to one will effect the other.
So, dump your row add event, and add the event directly in markup for the ddl as per above.
So, for buttons on each row, or whatever? You can still (and should) use markup to add those events - not code unless no other means exists to do so.
Edit: Working example
So, say this markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID"
CssClass="table"
Width="30%" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="Firstname" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:TemplateField HeaderText="Select Hotel City">
<ItemTemplate>
<asp:DropDownList ID="cboCity" runat="server" Width="120px" Height="26px"
DataTextField = "City"
DataValueField = "City"
AutoPostback="true"
OnSelectedIndexChanged="cboCity_SelectedIndexChanged"
>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Select Hotel">
<ItemTemplate>
<asp:DropDownList ID="cboHotels" runat="server" Width="210px" Height="26px"
DataValueField ="ID"
DataTextField ="HotelName">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nights" >
<ItemTemplate>
<asp:TextBox ID="txtNights" runat="server" Style="text-align:right"
Text='<%# Eval("Nights") %>' Width="70px" >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
We will cascade city combo to restrict Hotels in 2nd combo.
So, our code to load:
DataTable rstCity = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid ()
{
// load up City list for combo box - all rows (scope = page)
SqlCommand cmdSQL = new SqlCommand("SELECT City from City ORDER BY City");
rstCity = MyRstP(cmdSQL);
// load up the grid
cmdSQL.CommandText = "SELECT * from People ORDER BY FirstName";
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
We have this:
Note how we did NOT risk trying to set the DDL's in the markup - since we cascading - there will be way too many issues.
So, of course we have row data bound - and that sets up the two DDL's. (we setup the cascade AND ALSO set their values.
We have this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem; // get the row data
// load the city combo box
DropDownList cboCity = (DropDownList)e.Row.FindControl("cboCity");
cboCity.DataSource = rstCity;
cboCity.DataBind();
// add blank row for city
cboCity.Items.Insert(0, new ListItem("Select City", ""));
cboCity.SelectedValue = gData["City"].ToString(); // set value of Current city
// now load Hotel combo box - but cascade from above City cbo
string strSQL = #"Select ID, HotelName From tblHotels WHERE City = #City " +
" ORDER BY HotelName";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = gData["HotelCity"].ToString();
DropDownList cboHotels = (DropDownList)e.Row.FindControl("cboHotels");
DataTable rstHotels = MyRstP(cmdSQL);
cboHotels.DataSource = rstHotels;
cboHotels.DataBind();
cboHotels.Items.Insert(0, new ListItem("Select Hotel", ""));
// set hotels combo to current selected
cboHotels.SelectedValue = gData["Hotel_id"].ToString();
}
}
So, the only part left is the first DDL post-back and cascade code. We have this:
protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
{
// city changed, so cascade Hotel cbo
DropDownList cboCity = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
// filter hotels to current city
string strCity = cboCity.SelectedItem.Text;
DropDownList cboHotels = (DropDownList)gRow.FindControl("cboHotels");
if (strCity != "Select City")
{
SqlCommand cmdSQL = new
SqlCommand(#"SELECT * from tblHotels WHERE City = #City ORDER BY HotelName");
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = strCity;
cboHotels.DataSource = MyRstP(cmdSQL);
cboHotels.DataBind();
cboHotels.Items.Insert(0, new ListItem("Select Hotel", ""));
}
}
So, with above? I don't see how it is possible that some "other" row gets effected here (unless you have some other code that attempts to mess around with the rows, or inserts a row into the GV. If you going to insert a row, then insert at the database level - and re-bind the GV. But, inserting is a separate issue.
So here's the update where the second dropdown now functions correctly. However, when you click the update button, it will save correctly to the DB, but resets and clears out the second drowpdown list.
Markup:
<asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
ItemType="GetAGrip.Models.CartItem" CssClass="table table-striped table-bordered"
EnableViewState="true">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ID" SortExpression="ProductID" />
<asp:BoundField DataField="Product.ProductName" HeaderText="Name" />
<asp:BoundField DataField="Product.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="<%#: Item.Quantity %>"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Size">
<ItemTemplate>
<asp:DropDownList ID="Sizeddl" runat="server" Font-Size="Medium" OnSelectedIndexChanged="Sizeddl_SelectedIndexChanged"
AutoPostBack="true" ForeColor="Black" SelectedValue="<%#: Item.SizeName %>">
<asp:ListItem Selected="True" Text="Choose one" Value="0"></asp:ListItem>
<asp:ListItem Text="S" Value="S"></asp:ListItem>
<asp:ListItem Text="M" Value="M"></asp:ListItem>
<asp:ListItem Text="L" Value="L"></asp:ListItem>
<asp:ListItem Text="XL" Value="XL"></asp:ListItem>
<asp:ListItem Text="2XL" Value="2XL"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Color">
<ItemTemplate>
<asp:DropDownList ID="ColorNameddl" runat="server" Font-Size="Medium" ForeColor="Black">
</asp:DropDownList>
<asp:Label ID="Templbl" runat="server" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Total">
<ItemTemplate>
<%#: String.Format("{0:c}", ((Convert.ToDouble(Item.Quantity)) * Convert.ToDouble(Item.Product.UnitPrice)))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove Item">
<ItemTemplate>
<asp:CheckBox ID="Remove" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div>
<p></p>
<strong>
<asp:Label ID="LabelSubtotal" runat="server" Text="SubTotal: "></asp:Label>
<asp:Label ID="lblSubtotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
<p></p>
<strong>
<asp:Label ID="LabelTax" runat="server" Text="Tax Total: "></asp:Label>
<asp:Label ID="lblTax" runat="server" EnableViewState="false"></asp:Label>
</strong>
<p></p>
<strong>
<asp:Label ID="LabelTotalText" runat="server" Text="Order Total: "></asp:Label>
<asp:Label ID="lblTotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
</div>
<br />
<table>
<tr>
<td>
<asp:Button ID="UpdateBtn" runat="server" Text="Update" OnClick="UpdateBtn_Click" Visible="false" Enabled="false"/>
</td>
<th colspan="1"> 
</th>
<td>
<asp:ImageButton ID="CheckoutImageBtn" runat="server"
ImageUrl="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif"
Width="145" AlternateText="Check out with PayPal"
OnClick="CheckoutBtn_Click"
BackColor="Transparent" BorderWidth="0" />
</td>
</tr>
</table>
Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
}
using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
{
decimal cartTotal = 0;
cartTotal = usersShoppingCart.GetTotal();
if (cartTotal > 0)
{
// Display Total.
lblSubtotal.Text = String.Format("{0:c}", usersShoppingCart.GetSubtotal());
lblTax.Text = String.Format("{0:c}", usersShoppingCart.GetTax());
lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
}
else
{
lblSubtotal.Text = "";
lblTax.Text = "";
lblTotal.Text = "";
ShoppingCartTitle.InnerText = "Shopping Cart is Empty";
UpdateBtn.Visible = false;
CheckoutImageBtn.Visible = false;
}
}
}
Load Grid, Load Second DropDown List & Hide DDLs on rows they shouldn't be on:
void LoadGrid()
{
GetShoppingCartItems();
CartList.DataSource = GetShoppingCartItems();
CartList.DataBind();
var _db = new ProductContext();
for (int i = 0; i < CartList.Rows.Count; i++)
{
DropDownList sizeDDL = CartList.Rows[i].FindControl("Sizeddl") as DropDownList;
DropDownList colorDDL = CartList.Rows[i].FindControl("ColorNameddl") as DropDownList;
var _colors = (from c in _db.Colors
select c.ColorName).Distinct().ToList();
colorDDL.DataSource = _colors;
colorDDL.DataBind();
colorDDL.Items.Insert(0, new ListItem("Select Color", "0"));
colorDDL.SelectedIndex = 0;
foreach (ListItem item in colorDDL.Items)
{
item.Attributes.Add("disabled", "disabled");
}
IOrderedDictionary rowValues = new OrderedDictionary();
rowValues = GetValues(CartList.Rows[i]);
var _prodID = Convert.ToInt32(rowValues["ProductID"]);
var _prod = (from c in _db.Products
where c.ProductID == _prodID
select c.CategoryID).FirstOrDefault();
if (_prod != 1)
{
sizeDDL.Visible = false;
colorDDL.Visible = false;
}
}
}
GetShoppingCartItems Method:
public List<CartItem> GetShoppingCartItems()
{
ShoppingCartActions actions = new ShoppingCartActions();
return actions.GetCartItems();
}
UpdateCartItems Method
public List<CartItem> UpdateCartItems()
{
using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
{
String cartId = usersShoppingCart.GetCartId();
ShoppingCartActions.ShoppingCartUpdates[] cartUpdates = new ShoppingCartActions.ShoppingCartUpdates[CartList.Rows.Count];
for (int i = 0; i < CartList.Rows.Count; i++)
{
IOrderedDictionary rowValues = new OrderedDictionary();
rowValues = GetValues(CartList.Rows[i]);
cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ProductID"]);
CheckBox cbRemove = new CheckBox();
cbRemove = (CheckBox)CartList.Rows[i].FindControl("Remove");
cartUpdates[i].RemoveItem = cbRemove.Checked;
TextBox quantityTextBox = new TextBox();
quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
cartUpdates[i].PurchaseQuantity = Convert.ToInt16(quantityTextBox.Text.ToString());
DropDownList sizeDropDown = new DropDownList();
sizeDropDown = (DropDownList)CartList.Rows[i].FindControl("Sizeddl");
cartUpdates[i].SizeName = sizeDropDown.Text;
DropDownList colorDropDown = new DropDownList();
colorDropDown = (DropDownList)CartList.Rows[i].FindControl("ColorNameddl");
cartUpdates[i].ColorName = colorDropDown.Text;
}
usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates);
CartList.DataBind();
lblSubtotal.Text = String.Format("{0:c}", usersShoppingCart.GetSubtotal());
lblTax.Text = String.Format("{0:c}", usersShoppingCart.GetTax());
lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
return usersShoppingCart.GetCartItems();
}
}
GetValues Dictionary
public static IOrderedDictionary GetValues(GridViewRow row)
{
IOrderedDictionary values = new OrderedDictionary();
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.Visible)
{
// Extract values from the cell.
cell.ContainingField.ExtractValuesFromCell(values, cell, row.RowState, true);
}
}
return values;
}
Update Button Click
protected void UpdateBtn_Click(object sender, EventArgs e)
{
for (int i = 0; i < CartList.Rows.Count; i++)
{
UpdateCartItems();
}
Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
RowDataBound
protected void CartList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem; // get row data.
// load the color Drop Down List.
DropDownList sizeDDL = (DropDownList)e.Row.FindControl("Sizeddl");
sizeDDL.SelectedValue = gData["SizeName"].ToString();
//// Load Color DDL
var _size = sizeDDL.SelectedItem.Text;
int _prod = Convert.ToInt32(e.Row.Cells[0].Text);
var _db = new ProductContext();
var qryColor = (from p in _db.ProductAttributes
join c in _db.Colors
on p.ColorID equals c.ColorID
where p.SizeName == _size & p.ProductID == _prod
select new { p.ColorID, c.ColorName }).Distinct().ToList();
DropDownList colorDDL = (DropDownList)e.Row.FindControl("ColorNameddl");
// Bind Color Drop Down List to DataTable.
foreach (ListItem item in colorDDL.Items)
{
if (qryColor.Any(c => c.ColorName == item.ToString()))
{
item.Enabled = true;
}
}
colorDDL.SelectedValue = gData["ColorName"].ToString();
}
}
1st Dropdown SelectedIndexChanged
protected void Sizeddl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList sizeDDL = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)sizeDDL.NamingContainer;
string strSize = sizeDDL.SelectedItem.Text;
DropDownList colorDDL = (DropDownList)gRow.FindControl("ColorNameddl");
if (strSize != "Choose one")
{
using (ProductContext context = new ProductContext())
{
int _prodID = Convert.ToInt32(gRow.Cells[0].Text);
var _size = sizeDDL.SelectedItem.Text;
var qryColor = (from p in context.ProductAttributes
join c in context.Colors
on p.ColorID equals c.ColorID
where p.SizeName == _size & p.ProductID == _prodID
select new { p.ColorID, c.ColorName }).Distinct().ToList();
if (qryColor.Count > 0)
{
foreach (ListItem item in colorDDL.Items)
{
if (qryColor.Any(c => c.ColorName == item.ToString()))
{
item.Enabled = true;
}
else
{
item.Enabled = false;
}
}
colorDDL.Items[0].Enabled = true;
colorDDL.Enabled = true;
colorDDL.SelectedIndex = 0;
}
else
{
colorDDL.SelectedIndex = 0;
colorDDL.Enabled = false;
}
}
}
}
Anyplace you see a method that is not above, it's because it's a method in my Logic file to handle database queries for the whole application.
I'm trying to modify this asp.net / C# code. The page lets an admin add a user and choose what roles this user will have from a list of checkboxes. There are 11 checkboxes with roles next to them to pick from. I'm wanting to organize these checkboxes. I'm wanting to divide the 11 checkboxes into 3 groups CMS, LMS, and Admin in order to group them into three sections on the page. I'm wanting only one checkbox to be selectable for the CMS group. The CMS group can be a dropdown box if that would make it easier. And, all of these roles must have a tooltip when the user hovers their mouse over them.
You'll see in the code that the checkboxes get created using the userRolesDataSource. This datasource uses a method called "GetUserRoles" which has two parameters the "username" and the "onlyIncludeSystemAdminRole" boolean. The selection method checks if the username is a system admin and excludes all other role choices if this is true.
This is the new GetUserRoles method:
public List<Pair<string, bool>> GetUserRoles(
string userName, bool onlyIncludeSystemAdminRole)
{
// Return a list of "role name"/"has role" pairs for the given user.
// If the "onlyIncludeSystemAdminRole" flag is true, only return the
// "System Admin" role, otherwise return all roles other than
// "System Admin".
List<Pair<string, bool>> userRolesList = null;
if (!onlyIncludeSystemAdminRole)
{
string[] allRoles = Roles.GetAllRoles();
HashSet<string> rolesForUser = null;
if (!String.IsNullOrWhiteSpace(userName))
{
rolesForUser = new HashSet<string>(
Roles.GetRolesForUser(userName));
}
userRolesList = (from roleName in allRoles
where roleName != RoleNames.SYSTEM_ADMIN
select new Pair<string, bool>()
{
First = roleName,
Second = rolesForUser != null
? rolesForUser.Contains(roleName)
: false
}).ToList();
}
else
{
userRolesList = new List<Pair<string, bool>>()
{
new Pair<string, bool>(
RoleNames.SYSTEM_ADMIN,
Roles.IsUserInRole(userName, RoleNames.SYSTEM_ADMIN))
};
}
return userRolesList;
}
Something like that will still have to be run on all the checkboxes.
In order to solve the problem I planned on using something like this method. It can be given a list of roles as a parameter. And, it'll exclude the list provided and return every other role.
public IEnumerable<string> GetRoles(params string[] roleNamesToExclude)
{
var query = Uow.Roles
.AsQueryable()
.Select(r => r.RoleName);
if (roleNamesToExclude != null && roleNamesToExclude.Any())
{
query = query
.Where(r => !roleNamesToExclude.Contains(r));
}
return query.ToList();
}
My idea for re-building it was to replace userRolesDataSource with 3 new datasources: CMSRolesDataSource, LMSRolesDataSource, AdminRolesDataSource. Then create a new method that takes username, systemadmin boolean, as well as a list of excludable roles like the method above.
I'm still pretty new to coding and I'm wondering if there's a simpler way of doing all of this. The code to the asp and c# are below. Thanks in advance.
asp
<asp:ObjectDataSource ID="userRolesDataSource" runat="server" OnSelecting="userRolesDataSource_Selecting" OldValuesParameterFormatString="{0}" SelectMethod="GetUserRoles" TypeName="VirtualExpertClinics.AutismProClassroom.Data.UserBLL">
<SelectParameters>
<asp:Parameter Name="userName" Type="String" />
<asp:Parameter Name="onlyIncludeSystemAdminRole" Type="Boolean" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:ObjectDataSource ID="titlesDataSource" runat="server"
OldValuesParameterFormatString="{0}" SelectMethod="GetOrganizationTitles"
TypeName="VirtualExpertClinics.AutismProClassroom.Data.OrganizationBLL"
OnSelecting="titlesDataSource_Selecting">
<SelectParameters>
<asp:Parameter Name="organizationId" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
<h5><%: Resources.Global.UserRoles %></h5>
<asp:DataList ID="userRolesDataList" runat="server" CssClass="formTable" DataSourceID="userRolesDataSource" Enabled="false">
<ItemTemplate>
<asp:CheckBox ID="userRoleCheckBox" runat="server" Text='<%# Eval("First") %>' Checked='<%# Eval("Second") %>' />
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
<EditItemTemplate>
<asp:Panel ID="userDetailsPanel" runat="server" DefaultButton="saveButton">
<table class="formTable extraCellPadding">
<tr>
<td class="alignTop">
<asp:Label ID="userRolesLabel" runat="server" Text="<%$ Resources:Global, UserRoles %>"></asp:Label>
</td>
<td>
<asp:CustomValidator ID="userRolesCustomValidator" runat="server" ValidationGroup="validationGroup"
OnServerValidate="userRolesCustomValidator_ServerValidate" Display="Dynamic">*</asp:CustomValidator>
<asp:DataList ID="userRolesDataList" runat="server" CssClass="formTable" OnItemDataBound="userRolesDataList_ItemDataBound" DataSourceID="userRolesDataSource">
<ItemTemplate>
<asp:CheckBox ID="userRoleCheckBox" runat="server" Text='<%# Eval("First") %>' Checked='<%# Eval("Second") %>' />
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
<div style="margin-top: 1em;">
<asp:Button ID="saveButton" runat="server" CssClass="btn" ValidationGroup="validationGroup" CommandName="Update" Text="<%$ Resources:Global, Save %>" />
<asp:Button ID="cancelButton" runat="server" CssClass="btn" CommandName="Cancel" Text="<%$ Resources:Global, Cancel %>" />
</div>
</asp:Panel>
</EditItemTemplate>
<InsertItemTemplate>
<asp:Panel ID="userDetailsPanel" runat="server" DefaultButton="saveButton">
<table class="formTable extraCellPadding">
<tr>
<td class="alignTop">
<asp:Label ID="userRolesLabel" runat="server" CssClass="label" Text="<%$ Resources:Global, UserRoles %>"></asp:Label>
</td>
<td>
<asp:CustomValidator ID="userRolesCustomValidator" runat="server" ValidationGroup="validationGroup"
OnServerValidate="userRolesCustomValidator_ServerValidate" Display="Dynamic">*</asp:CustomValidator>
<asp:DataList ID="userRolesDataList" runat="server" CssClass="formTable" OnItemDataBound="userRolesDataList_ItemDataBound" DataSourceID="userRolesDataSource">
<ItemTemplate>
<asp:CheckBox ID="userRoleCheckBox" runat="server" Text='<%# Eval("First") %>' Checked='<%# Eval("Second") %>' />
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
<div style="margin-top: 1em;">
<asp:Button ID="saveButton" runat="server" CssClass="btn" ValidationGroup="validationGroup" CommandName="Insert" Text="<%$ Resources:Global, Save %>" />
<asp:Button ID="cancelButton" runat="server" CssClass="btn" CommandName="Cancel" Text="<%$ Resources:Global, Cancel %>" />
</div>
</asp:Panel>
</InsertItemTemplate>
</asp:FormView>
</div>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (SessionWrapper.ActiveUserID == null)
{
userFormView.ChangeMode(FormViewMode.Insert);
}
}
}
protected void detailDataSource_Inserting(
object sender, ObjectDataSourceMethodEventArgs e)
{
DataList userRolesDataList = (DataList)userFormView.Row.FindControl(
"userRolesDataList");
List<string> roles = GetSelectedUserRoles(userRolesDataList);
if (SessionWrapper.WorkingOrganizationId != null)
{
e.InputParameters["organizationId"]
= SessionWrapper.WorkingOrganizationId;
}
else
{
e.InputParameters["organizationId"]
= SessionWrapper.ActiveOrganizationID;
}
e.InputParameters["acceptedAgreement"] = false;
e.InputParameters["changedPassword"] = false;
e.InputParameters["mustUpdateProfile"] = true;
e.InputParameters["timeZoneId"] = TimeZoneInfo.Utc.Id;
e.InputParameters["roles"] = roles;
e.InputParameters["registrationCodeId"] = null;
e.InputParameters["createPasswordTicket"] = true;
MiscUtil.TrimInputParameters(e.InputParameters);
}
protected void detailDataSource_Updating(
object sender, ObjectDataSourceMethodEventArgs e)
{
DataList userRolesDataList = (DataList)userFormView.Row.FindControl(
"userRolesDataList");
e.InputParameters["roles"] = GetSelectedUserRoles(userRolesDataList);
UserProfileDS.UserProfileRow user = UserBLL.GetUserByUserID(
(Guid)userFormView.SelectedValue);
e.InputParameters["acceptedAgreement"] = user.AcceptedAgreement;
e.InputParameters["changedPassword"] = user.ChangedPassword;
e.InputParameters["mustUpdateProfile"] = user.MustUpdateProfile;
e.InputParameters["timeZoneId"] = user.TimeZoneId;
MiscUtil.TrimInputParameters(e.InputParameters);
}
protected void userRolesDataList_ItemDataBound(
object sender, DataListItemEventArgs e)
{
Pair<string, bool> rolePair = (Pair<string, bool>)e.Item.DataItem;
if (rolePair.First == RoleNames.CMS_OWNER
|| rolePair.First == RoleNames.CMS_DATA_ENTRY
|| rolePair.First == RoleNames.CMS_BROWSER)
{
// Disable the CMS roles if CMS access is not enabled for the
// current organization.
OrganizationDS.OrganizationRow organizationRow
= OrganizationBLL.GetOrganizationById(
SessionWrapper.ActiveOrganizationID);
if (!organizationRow.EnableCMS)
{
CheckBox userRoleCheckBox = (CheckBox)e.Item.FindControl(
"userRoleCheckBox");
userRoleCheckBox.Enabled = false;
userRoleCheckBox.ToolTip = Resources.Global.CMSNotEnabled;
}
}
else if (rolePair.First == RoleNames.WORKSHOPS_USER)
{
// Disable the "Workshops User" role if the corresponding
// check box is not selected and the current organization has
// reached their maximum number of learners.
if (!rolePair.Second
&& OrganizationBLL.HasReachedMaxLearners(
SessionWrapper.ActiveOrganizationID))
{
CheckBox userRoleCheckBox = (CheckBox)e.Item.FindControl(
"userRoleCheckBox");
userRoleCheckBox.Enabled = false;
userRoleCheckBox.ToolTip
= Resources.Global.OrganizationMaxLearnersReached;
}
}
else if (rolePair.First == RoleNames.LOCAL_SYSTEM_ADMIN)
{
// Disable the "Local System Admin" role if the current user
// is not a system admin.
if (!Roles.IsUserInRole(RoleNames.SYSTEM_ADMIN))
{
CheckBox userRoleCheckBox = (CheckBox)e.Item.FindControl(
"userRoleCheckBox");
userRoleCheckBox.Enabled = false;
}
}
}
protected void userRolesDataSource_Selecting(
object sender, ObjectDataSourceSelectingEventArgs e)
{
string userName;
bool onlyIncludeSystemAdminRole;
if (userFormView.CurrentMode == FormViewMode.Insert)
{
userName = "";
onlyIncludeSystemAdminRole
= (SessionWrapper.ActiveOrganizationID == 0);
}
else
{
UserProfileDS.UserProfileRow userRow
= (UserProfileDS.UserProfileRow)userFormView.DataItem;
userName = userRow.UserName;
onlyIncludeSystemAdminRole = Roles.IsUserInRole(
userRow.UserName, RoleNames.SYSTEM_ADMIN);
}
e.InputParameters["userName"] = userName;
e.InputParameters["onlyIncludeSystemAdminRole"]
= onlyIncludeSystemAdminRole;
}
private List<string> GetSelectedUserRoles(DataList userRolesDataList)
{
List<string> roles = new List<string>();
foreach (DataListItem item in userRolesDataList.Items)
{
CheckBox userRoleCheckBox = (CheckBox)item.FindControl(
"userRoleCheckBox");
if (userRoleCheckBox.Checked)
{
roles.Add(userRoleCheckBox.Text);
}
}
return roles;
}
protected void userRolesCustomValidator_ServerValidate(
object source, ServerValidateEventArgs args)
{
CustomValidator userRolesCustomValidator = (CustomValidator)source;
DataList userRolesDataList = (DataList)userFormView.Row.FindControl(
"userRolesDataList");
List<string> roles = GetSelectedUserRoles(userRolesDataList);
AdministrationUtil.ValidateUserRoleSelection(
roles, userRolesCustomValidator, args);
}
}
I want to force the user to change the selection of the first drop down list IF he/she selected a particular value in the second drop down list.
<asp:DropDownList ID="ddlGxP" runat="server" CssClass="stdDropdownSmall" OnSelectedIndexChanged="ddlGxP_SelectedIndexChanged" AutoPostBack="true" />
<
else
{
}
The above is the first drop down list where the user should select value from "ddlGxP"
The following is the second drop down list where I need to make the check when the user make a selection, I have to check on the first drop down.
<div class="divStandard">
<asp:Label ID="Label23" runat="server" CssClass="stdLabel">nalized Method <span class="mandatory"> *</span></asp:Label>
<asp:DropDownList ID="ddlFinalizedMethod" runat="server" CssClass="stdDropdown" />
<asp:CustomValidator ID="cvFinalizedMethod" runat="server" ControlToValidate="ddlFinalizedMethod" InitialValue="0" OnServerValidate="cvFinalizedMethod_ServerValidate"
CssClass="RequiredFieldError" ErrorMessage=" ! Please select another GxP Standard" />
} else {
<asp:TextBox ID="txtFinalizedMethodDisabled" runat="server" CssClass="stdTextboxSmallDisabled" Enabled="false" />
}
</div>
i don't have enough reputation so here is my comment.
i just want to clarify the problem in basic terms.
your design view consists of two dropdownlists.
you make a selection on dropdownlist1, its selectedindexchanged is triggered performing some sort of action.
you now make a selection on dropdownlist2, its selectedindexchanged is triggered and performs some sort of manipulation on dropdownlist1, either changing its contents or selected value;
SORRY FOR THE WAIT, I MADE SOME SIMPLE ERRORS DUE TO FORGETTING SOME THINGS;
The ANSWER!!!!
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
onselectedindexchanged="ddl2_selectindexchange">
</asp:DropDownList>
</div>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> str = new List<string>();
str.Add("red");
str.Add("blue");
str.Add("black");
List<string> str2 = new List<string>();
str2.Add("red");
str2.Add("blue");
str2.Add("black");
DropDownList1.DataSource = null;
DropDownList1.DataSource = str;
DropDownList1.DataBind();
DropDownList2.DataSource = null;
DropDownList2.DataSource = str2;
DropDownList2.DataBind();
}
}
protected void ddl2_selectindexchange(object sender, EventArgs e)
{
DropDownList ddl = new DropDownList();
ddl = sender as DropDownList;
ListItem li = new ListItem();
li = ddl.SelectedItem;
string s = li.Text;
Label1.Text = s;
}