Can't change DropDownList SelectedValue when Enabled = False in codebehind - c#

Good afternoon,
I have a DropDownList that I am setting Enabled = false in the code behind OnPageLoad. Later when I press the save button on the page I try to extract the data and I get a weird value from the disabled DropDownList and correct values from the Enabled DropDownList's.
My question is, how can I disable the DropDownList OnPageLoad so the users can't change the data but still modify it's data in the code behind file and extract it when needed? I see that the enabled property sets the read-only flag and I tried enabling the drop down before modifying it's data but it didn't work. Any ideas?
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 1; i <= Convert.ToInt32(txtNumPrizes.Text.Trim()); i++)
{
DropDownList dl = new DropDownList();
bool disableRow = true; //example
dl.ID = "DDPrize" + i.ToString();
dl.DataSourceID = "SqlDataSource1";
dl.DataTextField = "PrizeName";
dl.DataValueField = "PrizeID";
Panel1.Controls.Add(dl);
dl.DataBind();
if (disableRow == true)
{
dl.Enabled = false;
}
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
for (int i = 1; i <= Convert.ToInt32(txtNumPrizes.Text.Trim()); i++)
{
DropDownList dd = (DropDownList)Panel1.FindControl("DDPrize" + i.ToString());
//disable the row if prize was already assigned to a player
int place = 1; //example
int selectedValue = DropDownSelect(i, place, GetTournamentID());
dd.SelectedValue = selectedValue.ToString(); //sets properly here
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
for (int i = 1; i <= numPrizes; i++)
{
DropDownList dd = (DropDownList)Panel1.FindControl("DDPrize" + i.ToString());
string key = dd.SelectedValue;//here is where we can't get the selected value :(
}
}

If you disable it in code, then when it renders they can't change the selection. The SelectedItem will possibly be null/Nothing depending on whether you set any of the items to Selected=true.
It doesn't make much sense [to me, anyway] using a dropdown that can't be used. Unless of course it's waiting on a postback for enabling it based on certain criteria.
You could disable it with jQuery on page load, and .NET wouldn't care. No matter what, it will let you access the value, or lack thereof, which is what you might be missing. Again, you'll still run into the issue that there's no SelectedItem if you haven't set one in the web form or in code.
Posting the code will help us help you further :)

Related

Retain table and checked checkboxes after postback

In my webpage, I have Calendar, Table and button.
After selecting date, it will fire the databind() method of table. There are checkboxes with autopostback =true. Once checked, the Table disappears. I have no idea on how to retain the table with the checked checkboxes after post back.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString.Get("Id") != null)
{
if (!IsPostBack)
{
Calendar1.Visible = false;
}
}
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.ToShortDateString();
//Set datasource = (cal.selectedDate), the invoking override
// DataBind() method to create table
}
Calendar1.Visible = false;
}
I've tried to databind the table again else (IsPostBack) but i wasn't able to achieve my goals, instead, it created another table on top of the existing table
This is the method to create Table with checkboxes
public override void DataBind()
{
TableRow myTableRow = default(TableRow);
TableCell myTableCell = default(TableCell);
if (source != null && !(mDate == DateTime.MinValue))
{
for (int i = 0; i <= 23; i++)
{
foreach (DataRow row in source.Tables["Object"].Rows)
{
myTableCell = new TableCell();
CheckBox cb = new CheckBox();
cb.AutoPostBack = true;
cb.Attributes.Add("id", row["objid"].ToString());
cb.InputAttributes.Add("rowID", mDate.Date.AddHours(i).ToString());
myTableCell.Controls.Add(cb);
myTableCell.HorizontalAlign = HorizontalAlign.Center;
myTableRow.Cells.Add(myTableCell);
TimeSheetTable.Rows.Add(myTableRow);
}
}
}
else
{
throw new ArgumentException(" Invalid Date.");
}
}
Dynamically generated tables need to be regenerated on every postback. For subsequent postbacks, viewstate will be reloaded, but you have to recreate the table, cells, and controls in the same exact fashion, otherwise web forms complains about it. You need to do this during Init I believe; if checkbox checked status changed, the web forms framework will update the Checked property after load, so that will be taken care of.
I usually use a repeater or listview control as dynamic controls can be painful and the ListView is pretty flexible. Databinding takes care of rebuilding the control tree for you.

Textbox losing value after another buttons postback

On my page I have 3 textboxes that hold values for Title, Description, Tips and keywords. When I click on a button it inserts the values into the database. When it posts back, the values are staying in the textboxes, and this is what I want.
The next part of the page has textboxes for Question, CorrectAnswer, Wrong1, Wrong2, Wrong3. When I click on the button to insert them into the database, that works, and after the button fires its event I have those 5 textboxes have a text value of null, so I can continue on adding the question and answers.
But when that button causes its postback, the values in the first textboxes disappear, and I don't want that because I have validation on the title textbox, because you can't add any questions and answers without the title in the textbox.
So how do I keep the values in the first textboxes when the second button causes a postback?
Here is the code for the two buttons, and the btnAddQandA is the button that causes a postback..
protected void btnAddQuizTitle_Click(object sender, EventArgs e)
{
daccess.AddQuizName(tbTitle.Text, taDescription.InnerText, taTips.InnerText, tbKeywords.Text);
Session["TheQuizID"] = daccess.TheID;
string myID = (string)(Session["TheQuizID"]);
int theID = Int32.Parse(myID);
if (tbKeywords.Text != null)
{
string TheKeywordHolder = "";
foreach (ListItem LI in cblGrades.Items)
{
if (LI.Selected == true)
{
TheKeywordHolder = TheKeywordHolder + LI.Value + ",";
}
}
daccess.AddQuizKeywords(theID, tbKeywords.Text);
}
}
protected void btnAddQA_Click(object sender, EventArgs e)
{
int theID = (int)Session["TheQuizID"];
daccess.AddQuizQA(tbQuestion.Text, tbCorrect.Text, tbWrong1.Text, tbWrong2.Text, tbWrong3.Text, theID);
tbQuestion.Text = null;
tbCorrect.Text = null;
tbWrong1.Text = null;
tbWrong2.Text = null;
tbWrong3.Text = null;
}
and here is my pageload event
DataAccess daccess = new DataAccess();
protected void Page_Load(object sender, EventArgs e)
{
daccess.CblGradesDS();
cblGrades.DataSource = daccess.DsCbl;
cblGrades.DataValueField = "GradeID";
cblGrades.DataTextField = "Grade";
cblGrades.RepeatColumns = 8;
cblGrades.RepeatDirection = RepeatDirection.Horizontal;
cblGrades.DataBind();
daccess.CblSubjectsDS();
cblSubjects.DataSource = daccess.DsCbl2;
cblSubjects.DataValueField = "SubjectID";
cblSubjects.DataTextField = "SubjectName";
cblSubjects.RepeatColumns = 4;
cblSubjects.RepeatDirection = RepeatDirection.Horizontal;
cblSubjects.DataBind();
if (!IsPostBack)
{
}
}
These issues are usually caused by control IDs (UniqueIDs to be specific) that do not match before and after the postback. This causes inability of finding values in viewstate. This happens when you modify the controls collection (typically in codebehind) or when you change controls' visibility. It may also happen when you modify IDs before Page_Load event when viewstate is not yet populated. It's good to know how ASP.NET lifecycle works. http://spazzarama.com/wp-content/uploads/2009/02/aspnet_page-control-life-cycle.jpg

Retrieve the values from textbox which is dynamically created using C#

I have created few textbox dynamically while coding in the flow I have provided unique id for each and I have hard coded some values to all the text boxes using C#.
Now on click of button am trying to retrieve the values from the textbox for which I have used the below code, but its throwing an exception as OBJECT REFERENCE NOT SET TO INSTANCE OF AN OBJECT.
Please look at the below code, I have tried both the things but still am not getting. Please help me out.
Thanks
protected void btnPltGrap_onclick(object sender, EventArgs e)
{
//spny is my stack panel and txtX0 is my of the text box id
//Below is the 1st Try
TextBox tb = new TextBox();
tb= (TextBox)Master.FindControl("spnY").FindControl("txtX0");
string strx = tb.Text;
//Below is the 2nd Try
string strx = (spnY.FindControl("txtX0") as TextBox).Text;
}
Thanks
Am trying to use view state as per you told that i shlould recreate the controls ones again but am getting exception as Invalid Arguments. please go have a look.
protected void btnSet_onClick(object sender, EventArgs e)
{
Table tblMainY = new Table();
TableRow tblRow = new TableRow();
tblMainY.Controls.Add(tblRow);
TableCell tblCel = new TableCell();
TextBox txtdyn = new TextBox();
txtdyn.Text = "1";
txtdyn.ID = "txtY01";
txtdyn.Width = 50;
tblCel.Controls.Add(txtdyn);
tblRow.Controls.Add(tblCel);
splY.Controls.Add(tblMainY);
ViewState["temptbl"] = tblMainY
}
protected void btnPltGrap_onclick(object sender, EventArgs e)
{
splY.Controls.Add(ViewState["Temptbl"]);
}
Please help me out
I've had the same problem in the past.
What I did was give the dynamically-added control an ID, and made sure it retained that ID also on postback.
Once the postbacked control has the same ID as as before, Microsoft did magic and refilled the controls with the pre-postback values.
Read out this code once
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
this.NumberOfControls = 0; //very first time when page is loaded, value will be 0
else
this.createControls(); //if it is postback it will recreate the controls according to number of control has been created
}
//this is the base of this, it will hold the number of controls has been created, called properties
protected int NumberOfControls
{
get { return (int)ViewState["NumControls"]; }
set { ViewState["NumControls"] = value; }
}
//it will create the controls
protected void createControls()
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++) //loop for the total number of control.
{
TextBox tx = new TextBox(); //creating new control
tx.ID = "ControlID_" + i.ToString(); //in your solution you are giving static id, don't do that, assign id number dynamically, it will help you further, if you want to manipulate the controls for some other use
//Add the Controls to the container of your choice
form1.Controls.Add(tx);
}
}
//add new control
protected void addSomeControl()
{
TextBox tx = new TextBox();
tx.ID = "ControlID_" + NumberOfControls.ToString();
form1.Controls.Add(tx);
this.NumberOfControls++; //increment the number of control
}
protected void AddBtn_Click(object sender, EventArgs e)
{
addSomeControl();
}
Default.aspx
take placeholder tag in aspx file
< asp:PlaceHolder ID="PlaceHolder1" runat="server">
Default.aspx.cs
// adding/creating dynamic text box
TextBox txt = new TextBox();
txt.ID = "New_txt";
txt.TextMode = TextBoxMode.MultiLine;
txt.Text = dt.Rows[0]["message"].ToString();
txt.Width = 802;
txt.Height = 450;
txt.ReadOnly = true;
PlaceHolder1.Controls.Add(txt);
Retrive value from text box
string str = txt.Text;
some sample code in bellow link as my blog
Its explain for how to put and get textboxe's with values and validations in dynamicaly using panel control .
Let's go this url . and you can get good solutions
get and Create dynamic Textbox and dropdownlist with Validation
simple line for get textbox values in
TextBox objTextBox = (TextBox)PlaceHolder.FindControl("CorrecttextBoxName");
string value=objTextBox .Text;
You must recreate your controls on init to get it's value.
Here are some links
Get text from dynamically created textbox in asp.net
Edit 1
TextBox tb=(TextBox)ViewState["Temptbl"];
splY.Controls.Add(tb);

Make cells in a grid non-editable

In my syncfusion grid, I have to make some series cells non-editable based on the type.
If the type is an 'XXX' then the cell is editable,
If the type is a 'YYY','ZZZ' then cell is non-editable
So here;'s what I did.
private void theGrid_CurrentCellChanging(object sender, System.ComponentModel.CancelEventArgs e)
{
fp_data_typ typ;
int nSeries = theData.GetNumSeries();
for (int i = 0; i < nSeries; i++)
{
typ = theData.CheckType(i);
if (!(typ == 'XXX'))
{
e.Cancel = true;
}
}
}
I am not sure if I should be using theGrid_CurrentCellChanging event or theGrid_CurrentCellStartEditing. Documentation is not very clear. Gives me a ton of events to handle cell edit.
The code earlier works in an incorrect way. It does not work if the grid has a combination of editable and non-editable series. i:e if it has both xxx)editable and 'yyy'(non-editable), it makes both non-editable.
I was able to get the column index of the current cell and from there set e.cancel to true/false. Instead of setting e.cancel for the whole grid once, I went for the cell being edited.
Below events will help you to achieve your requirement.
//Use this if you want to control the ReadOnly setting while loading itself
grid.QueryCellInfo += new GridQueryCellInfoEventHandler(grid_QueryCellInfo);
void grid_QueryCellInfo(object sender, GridQueryCellInfoEventArgs e)
{
if (e.Style.CellValue.Equals("YYY"))
{
e.Style.ReadOnly = true;
}
}
//Use this if you want to Validate while Editing
grid.CurrentCellValidating += new CurrentCellValidatingEventHandler(grid_CurrentCellValidating);
void grid_CurrentCellValidating(object sender, CurrentCellValidatingEventArgs e)
{
//Will deactive the cell and new value will be discarded
//e.NewValue = e.OldValue;
//To remain in Edit mode without committing the vlaue
e.Cancel = true;
}
Thanks,
Sivakumar

Storing number of dynamically inserted controls for postback

I need to create the following functionality, and looking for the best way to store info on multiple postbacks:
Say I have a TextBox, that is related to a question, i.e. "Places I've visited". Once TextBox will be loaded on first load. Under that, there is a button to "Add another place". This will postback, which will then add another TextBox underneath the first. This can be done x number of times.
The question I have is, how do I store/remember the number of controls that have been added to the page by the user, considering that this load needs to be done in the Init event, and ViewState is not loaded at this point?
EDIT*:
I forgot to mention, that when the user saves, there would be some validation, so if validation fails, need to show all the TextBoxes, with their posted data.
If you were going to only allow a finite number of textboxes on your form, you could create that number of textboxes during Page_Init and set their visibility to false so they would not be rendered in the browser. On the button's click event, you could find the first invisible textbox and change the visibility to true. Something like this
protected void Page_Init(object sender, EventArgs e)
{
for (int i = 0; i < 20; i++)
{
this.Form.Controls.Add(new TextBox() { Visible = false });
}
}
protected void addTextboxButton_Click(object sender, EventArgs e)
{
TextBox tb = this.Form.Controls.OfType<TextBox>().FirstOrDefault(box => box.Visible == false);
if (tb != null) tb.Visible = true;
}
Using this approach, the textboxes become visible one by one on each button click, and the postback values stick.
Obviously, you'd want to put some more work into it, such as perhaps definining some literal controls to create line breaks and prompts for the textboxes, as well as displaying a message when the user hit whatever finite limit you set.
Option 1 : You can use Session to store the number of Textboxes...
Option 2 : You can even add controls in the Load event of the page, wherein you will have the ViewState information.
Here are the links that could help you...
TRULY understanding Dynamic Controls
Truly Understanding ViewState
After some thinking, and considering the answers given, came up with this solution.
In the controls placeholder, have a hidden input field which will store the number of controls added to the page. Then, on Init, I can have the following code (testing only):
protected override void OnInit(EventArgs e)
{
int i = 0;
i = Int32.Parse(hdnTestCount.Value);
if(Request.Params[hdnTestCount.UniqueID] != null)
{
i = Int32.Parse(Request.Params[hdnTestCount.UnitueID]);
}
for (int j = 1; j <= i; j++)
{
TextBox txtBox = new TextBox();
txtBox.ID = "Test" + j.ToString();
plhTest.Controls.Add(txtBox);
}
}
protected void btnAdd_OnClick(object sender, EventArgs e)
{
int i = 0;
i = Int32.Parse(hdnTestCount.Value) + 1;
TextBox txtBox = new TextBox();
txtBox.ID = "Test" + i.ToString();
plhTest.Controls.Add(txtBox);
hdnTestCount.Value = i.ToString();
}
Of course the only issue with this, is that the value could be manipulated by the user in the hidden field. The only other option would be to use Session, which I do not want to use as it sticks around, whereby if the page is refreshed this way, the form will reset itself, which is what should happen.

Categories

Resources