I work in ASP NET 4.0 and C-sharp.
I have one form page .aspx with this DropDownList (Inside is the ID) and save the value S or N in the matching field in database :
<asp:DropDownList ID="Inside" runat="server" Width="100" CssClass="ddl_Class">
<asp:ListItem Text="-------" Value=""></asp:ListItem>
<asp:ListItem Text="S" Value="S"></asp:ListItem>
<asp:ListItem Text="N" Value="N"></asp:ListItem>
</asp:DropDownList>
I need that when the value of field Inside in database is valid and is not null, in the DropDownList it's selected the value set in the database and disable the DropDownList.
I have tried this code in .cs page without success.
Anybody know how can I do that?
code-behind
InsideDB = dr["Inside"].ToString();
if (!string.IsNullOrEmpty(InsideDB.ToString()))
{
Inside.Text = InsideDB.ToString();
Inside.Enabled = false;
}
else
{
Inside.Enabled = true;
}
Try SelectedValue instead of Text property.
InsideDB = dr["Inside"].ToString();
Inside.Enabled = true;
if (!string.IsNullOrEmpty(InsideDB.ToString()))
{
Inside.SelectedValue = InsideDB.ToString();
Inside.Enabled = false;
}
Try something like
Inside.SelectedIndex = Inside.Items.IndexOf(Inside.Items.FindByText(InsideDB.ToString()));
instead of Inside.Text = InsideDB.ToString();
This assumes that you have an item with that text in the dropdownlist already.
I know this is old post. But this may help others.
Inside.Items.FindByText(InsideDB.ToString()).Selected=true;
Inside.Enabled = false;
Related
I'm currently running into a head-scratching bug in my ASP.NET Windows Form App. I have two DropDownList, implemented them in the same way, yet they behave differently.
The problem:
When selecting an item in the DropDownList "GroepSelect", the page refreshes (as intended), but resets it's SelectedIndex to the first item.
When selecting an item in the DropDownList "VakSelect", the page refreshes, but also remembers it's SelectedIndex value.
It's doing this behavior consistently, yet I am unable to discover what I do wrong.
My Code:
In my HTML code, I have two DropDownList Controls.
<div>
<asp:DropDownList runat="server" ID="GroepSelect" AutoPostBack="true" AppendDataBoundItems="true" />
<asp:DropDownList runat="server" ID="VakSelect" AutoPostBack="true" AppendDataBoundItems="true" />
</div>
I'm populating the controls in my C# code:
protected void Page_Load(object sender, EventArgs e) {
Database db = new Database();
if (!IsPostBack) {
GroepSelect.DataSource = GenereerDummyGroepen(); // returns a List<ListItem>
GroepSelect.DataTextField = "Text";
GroepSelect.DataValueField = "Value";
GroepSelect.DataBind();
GroepSelect.SelectedValue = "1";
VakSelect.DataSource = db.GetVakken(); // returns a List<Vak>
VakSelect.DataTextField = "Omschrijving";
VakSelect.DataValueField = "Id";
VakSelect.DataBind();
VakSelect.SelectedValue = "1";
}
// Use the SelectedValue to determine which data to get out of the database
Medewerkers = db.GetMedewerkers(int.Parse(GroepSelect.SelectedValue));
Opdracht = db.GetOpdrachten(int.Parse(VakSelect.SelectedValue)).First();
Resultaten = db.GetResultaten(Opdracht.Id, int.Parse(GroepSelect.SelectedValue));
GenereerTabel();
}
As requested, my code for GenereerDummyGroepen() is the following:
private List<ListItem> GenereerDummyGroepen() {
return new List<ListItem>()
{
new ListItem("Groep 1", "1"),
new ListItem("Groep 2", "1")
};
}
Why I implemented it this way?
I try to populate a custom-made pivot table based on the content of Medewerkers, Opdracht and Resultaten. The content of those lists, depends on the selected item in the DropDownList control. The expected behavior of those controls is, that on the moment those are changed, the table should re-populate. The strategy I follow here, is that a page-postback is being processed, and using the AppendDataBoundItems=true remembers the DropDownList contents so that on the newly refreshed page I can generate the table.
My Question
I'm looking for the answer for: why is there a consistent different behavior? Is it the fact that the ListItem class differs in behavior from my custom class Vak?
Here I guess issue is with you function
GenereerDummyGroepen();
Please put your code here. In your code there is value field might have same data for all listItem. Because of that it is changing default to firstIndex as all values are same.
Let say I want to hide one of the radio buttons with value 0, what code can make it visible = false? I was using Javascript, C# and ASP.NET.
<asp:ListItem Value="1"> 1 </asp:ListItem>
<asp:ListItem Value="2"> 2 </asp:ListItem>
<asp:ListItem Value="3"> 3 </asp:ListItem>
<asp:ListItem Value="4"> 4</asp:ListItem>
<asp:ListItem Value="0" Selected="True" Enabled="False">
foreach (ListViewDataItem item in ListView1.Items)
{
var rbl = (RadioButtonList)item.FindControl("rblSelect");
var selectedValue = int.Parse(rbl.SelectedItem.Value);
var selectedText = rbl.SelectedItem.Text;
var selectedIndex = rbl.SelectedIndex;
rbl.Items[0].Attributes.CssStyle.Add("visibility", "hidden");
}
Try This : From CodeBehind
MyRadioButtonList.Items[0].Attributes.CssStyle.Add("visibility", "hidden");
EDIT:
int count = 0; //index of item tobe hidden
foreach (ListViewDataItem item in ListView1.Items)
{
var rbl = (RadioButtonList)item.FindControl("rblSelect");
var selectedValue = int.Parse(rbl.SelectedItem.Value);
var selectedText = rbl.SelectedItem.Text;
var selectedIndex = rbl.SelectedIndex;
if(count == 0)
rbl.Attributes.CssStyle.Add("visibility", "hidden");
count++;
}
try this
rbl.Items[0].Enabled = false;
Use the following:
MyRadioButtonList.Items[0].Attributes.CssStyle.Add("display", "none");
In javascript it's possible to hide it with ".style.display"
var radio = document.getElementById('idOfYourRadiobutton');
radio.style.display = 'none'; // to hide
radio.style.display = 'block'; // to show
You need to amend the code as follows:
rdBtn.items.remove("name_of_the_item");
In this case, the rdBtn is the RadioButtonList ID
You can try this if you don't want to display it:
ListView1.Items.FindByValue("0").Attributes.CssStyle.Add("display", "none")
Changes ("display", "none") to ("visibility", "hidden") to hide it.
What is the different between hide and none display?
Well, if you hide a radio button between two other radio buttons, there is still a space between two those button. If you don't display it, there is no such weird space.
I would like to know how to maintain the control state that has been modified in Javascript.
I have two TextBoxes, one DropDownList and a button (all Runat=Server) in C# ASP.net 2010 Express.
First textbox is just accept whatever data user input. Second textbox enable state will change based on DDL selected value. If ddl selected value is "-", second textbox will become Enabled = False.
If not "-", it will become Enabled = True. This enable is done through Javascript.
In my Page Load event, I have below code.
if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
And in my aspx page, I have some javascript which will clear the textbox data and disable the textbox.
Here is for Second Textbox.
<asp:TextBox ID="txtKey2" runat="server" Width="425px" EnableViewState="False"></asp:TextBox>
And here is for DDL.
<asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
Here is the code for my Javascript. (I have a plan to implement other textbox and ddl so in my code I have Else if condition).
function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
I have nothing in button click event.
By using above all code, when I run the project, the page loads Ok.
The second textbox enabled state is set to False (through Page_Load event). So far Ok.
Then from my browser, I choose ddl value to other instead of "-", the textbox become enable because of javascript. This is Ok.
I input the value and click on the button. Page PostBack happens here. Textbox is still enabled (because of EnableViewState = False for my textbox).
I choose ddl value to "-", second textbox became disabled.
Click on the button, page postback happen, but this time the textbox is still enabled. << This is the issue I'm trying to solve. I change EnableViewState, ViewStateMode in different values but still the same.
Is there any solution for this one?
Here is my test image URL.
State 1 ,
State 2 ,
State 3
Sorry for the long post.
I have tried and found no solution beside using additional HiddenField control.
I update the hidden field value when I update the status of my textbox in Javascript.
And on my Page Load event, I checked all the hidden field values and based on the hiddenfield values, I will disable/enable my textboxes which is for me not a good solutions.
Imagine I have 10 or 15 textboxes on my form, I need to have 10 or 15 hidden field just to maintain client side action result.
Currently, this is the only solution for me.
I'm not sure can this consider as 'Answer' so I haven't close this question yet.
<asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
You Have to call you javascript function on every postback.
if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
ScriptManager.RegisterClientScriptBlock(this, typeof(System.Web.UI.Page), "MyJSFunction", "EnableSelkey("+selKey1.SelectedValue+",1);", true);
It May be help you, Let me know for further help.
I found a solution that worked was to put the code that I put in the !IsPostBack section for enabling and disabling the textboxes also directly in the page load event.
I get the SelectedValue = "" when i click on My button .
My aspx :
<telerik:RadComboBox ID="ddl_contactList" runat="server" AutoPostBack="True" CausesValidation="False"
CollapseDelay="0" Culture="ar-EG" ExpandDelay="0" Filter="StartsWith" ItemsPerRequest="10"
MarkFirstMatch="true" Skin="Outlook" EnableAutomaticLoadOnDemand="True" EmptyMessage="-New Menu-"
ShowMoreResultsBox="True" OnSelectedIndexChanged="ddl_contactList_SelectedIndexChanged"
EnableItemCaching="false" EnableLoadOnDemand="True" EnableVirtualScrolling="True">
</telerik:RadComboBox>
My .cs :
private void BindContactLists(int year, int main_code)
{
ddl_contactList.Items.Clear();
DataTable dt = ContactList.GetContactListsByDep(year, main_code);
ddl_contactList.DataSource = dt;
ddl_contactList.DataTextField = "list_desc";
ddl_contactList.DataValueField = "list_code";
ddl_contactList.DataBind();
}
I call it in the page load because when I call it in the
!Page.Ispostback, I get the following error:
There is no assigned data source. Unable to complete callback request.
How can I fix this problem? Right now:
ddl_contactList.Text == "MySelectedItemText"
but
selectedValue == "" and selectedItem == ""
Move your call to BindContactLists() from the Page_Load() method to the Page_Init() method. This allows the control to be setup for ViewState binding later in the page lifecycle, and allow proper population of the SelectedValue property.
It's normal because you re-bind your datas => so you erase your selected value
I suggest you to set your block in !IsPostBack => you don't erase when you post
In PageLoad
if(! IsPostBack)
{
ddl_contactList.Items.Clear();
DataTable dt = ContactList.GetContactListsByDep(year, main_code);
ddl_contactList.DataSource = dt;
ddl_contactList.DataTextField = "list_desc";
ddl_contactList.DataValueField = "list_code";
ddl_contactList.DataBind();
}
And you persist your control with ViewState
Set EnableViewState="true"
make sure your datasource like dataset or datatable fill when page load or init fire
The controls on aspx page are like this
Submitted
Submission Date
I want, if the check box is checked, then the textbox will be enabled I wrote
if(chkSubmitted.Checked)
{
txtSubmissionDate.Enabled = true;
}
in the page load event. But when the page is loaded this checkbox having no effect on. Whats going wrong?
If you want the action of clicking the checkbox to enable the textbox, you'll need to do a postback when the box is checked by setting AutoPostBack="True":
<asp:CheckBox runat="server" ID="chkSubmitted" AutoPostBack="True" />
Or, you could use JavaScript:
<asp:CheckBox runat="server" ID="chkSubmitted" onclick="setSubmissionDateEnabled()" />
function setSubmissionDateEnabled()
{
var chkSubmitted = document.getElementById("<%= chkSubmitted.ClientID %>");
var txtSubmissionDate = document.getElementById("<%= txtSubmissionDate.ClientID %>");
txtSubmissionDate.disabled = !chkSubmitted.checked;
}
First set autopostback property to true of checkbox
write following code in checkbox_Selectedindexchanged event
if(chkSubmitted.Checked)
{
txtSubmissionDate.Enabled = true;
}
else
{
txtSubmissionDate.Enabled = false;
}
Thats most likely because the default state of txtSubmissionDate is enabled already.
Try this in your page_load:
txtSubmissionDate.enabled = !chkSubmitted.Checked
To clarify, the textbox should not (!) be enabled when the Checkbox is.
Put this in Page_PreRender event. At this stage it will capture the user affected state of chkSubmitted.