c# 2nd dropdownlist fail retain the value when submit - c#

protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
filldropdown(dllselection.SelectedValue);
Code.Enabled = true;
if(dllselection.SelectedValue=="")
{
Code.Enabled = false;
}
}
}
i think there something wrong with the page load,my 2nd dropdownlist is depend on 1st dropdownlist selection.
<div class="form-group">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label" style="color:black" >Main Category</label>
<div class="col-sm-3">
<asp:DropDownList ID="dllselection" runat="server" CssClass="form-control" AutoPostBack="true" required>
<asp:ListItem Text="Please Select" Value=""></asp:ListItem>
<asp:ListItem Text="HR" Value="M_1"></asp:ListItem>
<asp:ListItem Text="IT" Value="M_2"></asp:ListItem>
<asp:ListItem Text="Maintenance" Value="M_3"></asp:ListItem>
</asp:DropDownList>
</div>
</div>
<div class="form-group">
<label for="Training" style="color:black" class="col-sm-2 control-label">Sub Category</label>
<div class="col-sm-3">
<asp:DropDownList ID="Code" Enabled="false" onchange="javascript:return dropdown(this);" runat="server" CssClass="form-control" ValidationGroup="G1" required></asp:DropDownList>
</div>
</div>
everytime i submit pass data to database,the value for the 2nd dropdownlist always the 1st value.
public void filldropdown(string item)
{
int loggedUserID = Convert.ToInt32(Session["loggedUserID"]);
List<BOL.UserInfo> userslist = new UserInfos().List();
BOL.UserInfo loggeduser = userslist.Where(x => x.UserID == loggedUserID).FirstOrDefault();
// int ID = 10;
List<e_request> role = new e_requests().dropdownlistG(loggeduser.SUBSIDIARY_CD, item);
Code.DataSource = role;
Code.DataTextField = "CAT_DESC";
Code.DataValueField = "SUB_CAT";
Code.DataBind();
}

You can filling drop down on postback which you should not if you want to keep selection. use !Page.IsPostBack instead of Page.IsPostBack
Change
if (Page.IsPostBack)
{
To
if (!Page.IsPostBack)
{
On more thing you may need to put condition out side !Page.IsPostBack as you would need it to be executed on postback
if (!Page.IsPostBack)
{
filldropdown(dllselection.SelectedValue);
}
Code.Enabled = true;
if(dllselection.SelectedValue=="")
{
Code.Enabled = false;
}
Also note you may need to fill the second dropdown on SelectedIndexChange of dllselection and need to set AutoPostBack of dllselection true.

Try this:
if (!IsPostBack)
{
if (dllselection.SelectedValue == "")
{
Code.Enabled = false;
}
else
{
Code.Enabled = true;
filldropdown(dllselection.SelectedValue);
}
}

Try to Load Method in
if (!Page.IsPostBack)
{
filldropdown(dllselection.SelectedValue);
Code.Enabled = true;
if(dllselection.SelectedValue=="")
{
Code.Enabled = false;
}
}
Update:
you need to fill the second dropdown on SelectedIndexChange of dllselection and need to set AutoPostBack = true of dllselection .

<asp:DropDownList ID="logList" runat="server" AutoPostBack="True"
onselectedindexchanged="itemSelected">
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){
filldropdown(dllselection.SelectedValue);
Code.Enabled = true;
if(dllselection.SelectedValue=="")
{
Code.Enabled = false;
}
}
}

add OnSelectedIndexChanged="dllselection_SelectedIndexChanged" to my 1st dropdownlist.
protected void dllselection_SelectedIndexChanged(object sender, EventArgs e)
{
if (dllselection.SelectedIndex == 0)
{
Code.Enabled = false;
}
else
{
Code.Enabled = true;
//fill Code
filldropdown(dllselection.SelectedValue);
}
}

Related

How to set 3 radiobutton with its groupname in a repeater

I need to set 3 different groups of radio button in a repeater. Using groupname property for it wasn't enough. So, after researching, I use a bit of JS and it works. My problem is when I want to implement more than one group of radiobuttons. Can anyone help me?
My best approach is:
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
</span>
</ItemTemplate>
</asp:Repeater>
JS
<script>
function SetUniqueRadioButton(nameregex, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'radio') {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('repeaterImages.*nombreLogo',this)";
string scriptApp = "SetUniqueRadioButton('repeaterImages.*nombreLogoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('repeaterImages.*nombreLogoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
With this code just getting 3 rows of radiobutton, sharing groupname behavior for all of them... (I want groupname behavior per row...)
Piece of cake. Prove how newie I am in JS. I am posting the solution because is a recurrent issue in asp programming and this bug is known. Beside I cant find the solution for some radio button.
JS.
<script>
function SetUniqueRadioButton(text, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if ((elm.type == 'radio') && (elm.value == text)) {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('rbLogoSeleccionado',this)";
string scriptApp = "SetUniqueRadioButton('rbLogoSeleccionadoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('rbLogoSeleccionadoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
</span>
</ItemTemplate>
</asp:Repeater>

ASP.NET Update Webpage when 'OnCheckedChanged'

I'm trying to show controls on my webpage when someone clicks a NewUser checkbox but I cant get it working.
Webpage Screenshot
This is my Login.aspx code:
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
<asp:CheckBox runat="server" ID="NewUser" OnCheckedChanged="UpdateOptions" />
<asp:Label runat="server" AssociatedControlID="NewUser">New User?</asp:Label>
</div>
</div>
</div>
This is my Login.aspx.cs code:
//DM Create event to make controls visible if check box is selected
public void UpdateOptions(object update, EventArgs e)
{
if(NewUser.Checked == true)
{
ConfirmEmailLabel.Visible = true;
TextBox3.Visible = true;
ConfirmPasswordLabel.Visible = true;
TextBox4.Visible = true;
Firstname.Visible = true;
TextBox1.Visible = true;
Lastname.Visible = true;
TextBox2.Visible = true;
}
else
{
ConfirmEmailLabel.Visible = false;
TextBox3.Visible = false;
ConfirmPasswordLabel.Visible = false;
TextBox4.Visible = false;
Firstname.Visible = false;
TextBox1.Visible = false;
Lastname.Visible = false;
TextBox2.Visible = false;
}
}
Any ideas would be much appreciated?
Add this
<asp:CheckBox runat="server" ID="NewUser" OnCheckedChanged="UpdateOptions" AutoPostBack="true"/>
You should set true AutoPostBack property of checkbox.
<asp:CheckBox runat="server" AutoPostBack="True" ID="NewUser" OnCheckedChanged="UpdateOptions" />

ViewState won't hold dynamically created controls' value, even though I preserve the same ids in postbacks

I am trying to create a simple form generating webpage that user can select different controls via a DropDownList, add a Text property to it(and a GroupName property if ii was a RadioButton) and then click a button to generate that control right in the page for previewing purpose (I am also going to add another button to insert the form's information in a database but this is not my problem right now)
this is my aspx page:
<div class="main-wrapper">
<form dir="rtl" id="form" runat="server">
<label>Desired Control : </label>
<asp:DropDownList AutoPostBack="true" ID="ddlControlType" OnSelectedIndexChanged="ddlControlType_SelectedIndexChanged" runat="server">
<asp:ListItem Text="label"></asp:ListItem>
<asp:ListItem Text="text box"></asp:ListItem>
<asp:ListItem Text="check box"></asp:ListItem>
<asp:ListItem Text="radio button"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<label class="label">control's text : </label>
<asp:TextBox ID="txtboxText" runat="server" CssClass="txtbox"></asp:TextBox>
<label class="label">group name (only for radio button)</label>
<asp:TextBox Enabled="false" ID="txtboxGroupName" runat="server" CssClass="txtbox"></asp:TextBox>
<br /><br />
<asp:Button ID="btnAddControl" CssClass="btn" Text="add to form" OnClick="btnAddControl_Click" runat="server" />
<hr />
<h1>form preview</h1>
<asp:Panel ID="panel" runat="server">
</asp:Panel>
</form>
this is the code behind:
public Dictionary<string, Type> ControlTypes
{
get { return (Dictionary<string, Type>)Session["ControlTypes"]; }
set { Session["ControlTypes"] = value; }
}
public int NumberOfControls
{
get { return (int)ViewState["NumOfControls"]; }
set { ViewState["NumOfControls"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.NumberOfControls = 0;
ControlTypes = new Dictionary<string, Type>();
}
else
this.CreateControls();
}
private void CreateControls()
{
for (int counter = 0; counter < this.NumberOfControls; counter++)
{
string controlId = "control_id_" + counter.ToString();
Type controlType = ControlTypes[controlId];
PropertyInfo[] properties = controlType.GetProperties();
object controlObject = Activator.CreateInstance(controlType);
foreach (var property in properties)
{
if (property.Name == "ID")
property.SetValue(controlObject, controlId, null);
}
panel.Controls.Add(controlObject as Control);
}
}
protected void ddlControlType_SelectedIndexChanged(object sender, EventArgs e)
{
switch (ddlControlType.SelectedIndex)
{
case 0:
case 2:
txtboxText.Enabled = true;
txtboxGroupName.Enabled = false;
break;
case 1:
txtboxText.Enabled = false;
txtboxGroupName.Enabled = false;
break;
case 3:
txtboxText.Enabled = true;
txtboxGroupName.Enabled = true;
break;
}
}
protected void btnAddControl_Click(object sender, EventArgs e)
{
Control tempControl = null;
switch (ddlControlType.SelectedIndex)
{
case 0:
tempControl = new Label();
((Label)tempControl).Text = txtboxText.Text;
break;
case 1:
tempControl = new TextBox();
break;
case 2:
tempControl = new CheckBox();
((CheckBox)tempControl).Text = txtboxText.Text;
break;
case 3:
tempControl = new RadioButton();
((RadioButton)tempControl).Text = txtboxText.Text;
((RadioButton)tempControl).GroupName = txtboxGroupName.Text;
break;
}
string controlId = "control_id_" + this.NumberOfControls.ToString();
tempControl.ID = controlId;
panel.Controls.Add(tempControl);
this.NumberOfControls++;
ControlTypes.Add(controlId, tempControl.GetType());
}
as you can see, I preserve the id's of the controls, but the viewstate won't update their values.the controls will be added to the form with the desired id, but its values won't be set at all
what should I do?

How to set a linkbutton's state based on a condition?

I've got 2 linkbuttons, they are linked to a multiview and depending on which I push will change the active view. I want the linkbutton of it's respective view to appear as it is active state.
<asp:Panel runat="server" >
<div>
<asp:LinkButton ID="linkDeviceList" CommandName="SwitchViewByID" CommandArgument="viewDeviceList" runat="server" OnClick="linkDeviceList_Click" CssClass="button-link">Device List</asp:LinkButton>
<asp:LinkButton ID="linkFTPFolders" CommandName="SwitchViewByID" CommandArgument="viewFTPFolders" runat="server" OnClick="linkFTPFolders_Click" CssClass="button-link">FTP Folders</asp:LinkButton>
</div>
</asp:Panel>
The event handlers. I assumed I'd change the button's state in a 'while' but can't figure out how to apply the style change.
protected void linkFTPFolders_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(viewFTPFolders);
while (MultiView1.GetActiveView() == viewFTPFolders)
{
}
}
protected void linkDeviceList_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(viewDeviceList);
while (MultiView1.GetActiveView() == viewDeviceList)
{
}
}
I have a similar control. And this is what I did.
I removed/added the "active" class on the button that was clicked.
I disabled the button that was clicked so that it can't be clicked
again.
protected void lbListView_Click(object sender, EventArgs e)
{
lbGridView.CssClass = "btn btn-default btn-sm pull-right dt-margin-left-5";
lbGridView.Enabled = true;
lbListView.CssClass = "btn btn-default btn-sm pull-right dt-margin-left-5 active";
lbListView.Enabled = false;
repGridResults.Visible = false;
repListResults.Visible = true;
}
protected void lbGridView_Click(object sender, EventArgs e)
{
lbListView.CssClass = "btn btn-default btn-sm pull-right dt-margin-left-5";
lbListView.Enabled = true;
lbGridView.CssClass = "btn btn-default btn-sm pull-right dt-margin-left-5 active";
lbGridView.Enabled = false;
repListResults.Visible = false;
repGridResults.Visible = true;
}

Looping through repeater items

I have a repeater which is built like the following:
<asp:Repeater runat="server" ID="rptItems" OnItemDataBound="rptItems_ItemDataBound">
<ItemTemplate>
<div class="span12 grey-box">
<div class="hero-block3">
<div class="row show-grid">
<div class="span9">
<div class="hero-content-3">
<h2><asp:Literal ID="ltrName" runat="server"></asp:Literal></h2>
<p><asp:Literal ID="ltrDescription" runat="server"></asp:Literal></p>
</div>
</div>
<div class="span3">
<asp:Panel ID="pnlAmount" runat="server">
<div class="tour-btn" id="divAmount" runat="server">
<small>How Many?<br /></small>
<asp:TextBox runat="server" ID="tbox" Width="40"></asp:TextBox>
</div>
</asp:Panel>
</div>
</div>
</div>
</div>
<div class="clear-both"></div>
<br />
</ItemTemplate>
</asp:Repeater>
It's bound using:
ListProducts = db.GetDataTable("select * from Products where Id in (" + selectedValues + ")");
rptItems.DataSource = ListProducts;
rptItems.DataBind();
And then extra stuff is done with:
protected void rptItems_ItemDataBound(object sender,
System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
DataRowView nRow = null;
switch (e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
nRow = (DataRowView)e.Item.DataItem;
((Literal)e.Item.FindControl("ltrDescription")).Text = "" + nRow["Description"];
((Literal)e.Item.FindControl("ltrName")).Text = "" + nRow["Name"];
if ("" + nRow["HasAmount"] == "False")
{
((Panel)e.Item.FindControl("pnlAmount")).Visible = false;
}
break;
}
}
However, now on an onclick event for the page, i'm trying to save the information stored - This is what i've done so far, but it always all seems to be null, and I can't add a .text etc to the end of the (TextBox)item.FindControl("tbSelected");
Heres my loop i'm trying on click:
protected void doStageThree(object sender, EventArgs e)
{
foreach (RepeaterItem item in rptItems.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
var tbSelected = (TextBox)item.FindControl("tbSelected");
var lblDescription = (Literal)item.FindControl("ltrDescription");
var lblName = (Literal)item.FindControl("ltrName");
}
}
}
It is always null because there is no TextBox with id tbSelected
<asp:TextBox runat="server" ID="tbox" Width="40"></asp:TextBox>
change it to:
var tbSelected = (TextBox)item.FindControl("tbox");
To protect your code from null use keyword as:
var tbSelected = item.FindControl("tbox") as TextBox;
if (tbSelected != null)
{
//textbox with id tbox exists
tbSelected.Text = "your text";
}
Try replacing
foreach (RepeaterItem item in rptItems.Items)
with
foreach (Control c in rptItems.Items)
{
if(c.FindControl("tbSelected") != null)
{
var selectedText = ((TextBox)c.FindControl("tbSelected")).Text;
}
}

Categories

Resources