Asp.Net Toggle checked property of a Data Bound checkbox - asp.net

I have a GridView control that has one column of checkboxes set up like this:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="RowCheckBox" runat="server" Enabled="false" Checked='<%# (bool)DataBinder.Eval(Container.DataItem ,"Associated") %>'/>
</ItemTemplate>
</asp:TemplateField>
Then when the user clicks an Edit button I run a script that enables all the checkboxes (which works fine), and then when the user then clicks on a checkbox the tick is appearing or disappearing as it should.
The problem I'm having is that when I try to read the value of the checkbox from the codebehind:
CheckBox checkBox = (CheckBox) row.FindControl("RowCheckBox");
bool checked = checkBox.Checked;
If the value bound to it was true then checked is still true, no matter if it was toggled or not.
Has anyone got any ideas why this is?

In the end I couldn't find a solution so have done a work around:
Add a Hidden Field to the Template Field,
Update the value of the hidden field to True or False with Javascript (adding an onclick attribute to the checkbox),
In the code behind cast the hidden field value to a bool and use that instead of the checked property of the checkbox.
I think it might be something to do with View States, but I'm not sure what they are and haven't got the time to investigate unfortunately.
Clivest

Related

Disabling an ASP.net textbox without actually disabling it?

Within an ASP.Net application I have, there is a textbox that gets a date from a CalendarExtender. When the textbox is populated it checks that date with another date on the form and displays a modalpopupextender popup if the dates are wrong. However, I DO NOT want to allow user input into this textbox, so when I set the ReadOnly field to false and tried Enabled to false, it doesn't allow manual entry however it ALSO disabled the postback and will not call the TextChanged event to fire the modalpopupextender.
So is there a way to disable manual entry and not set it to ReadOnly?
I figured it out, simply enter onkeypress="return false;" within the HTML tag
Try this
<asp:textbox id="txt1" onfocus="blur()" runat="server"/>
this worked for me.
Add the below properties in the tag of textbox
onkeydown="return false" onpaste="return false"
ex:
<asp:TextBox ID="TillDate_TextBox" runat="server" onkeydown="return false" onpaste="return false"></asp:TextBox>
the first property block typing in textbox and the second property block pasting in it
I'm not familiar with the exact components you are using, however the usual way to accomplish things like this is the following. Have selecting the date on the calendar modify the value of a hidden form field. This will restrict the user from editing the value directly. Then create another element like a div or a span, and use javascript to update the span/div to the value selected on the calendar.

Setting Visibility of Button Control in GridView Header

I have a gridview that displays entries from a data table. I am giving users the ability to select a subset of the data in the table by having a textbox and search button in the grid view header. The search button fires the gridview row command, and changes the underlying sqlDataSource's select command, and adds the text value from the text box as a parameter.
This works smoothly.
Also, I have a "Show All" button in the header, that clears out the select parameters, so all entries in the table are shown. Again, this works perfectly.
What is NOT working is controlling the visibility of the "Show All" button control. Below is the html markup for the data grid header template:
<HeaderTemplate>
<asp:Button ID="btnShowAll" runat="server" CausesValidation="False" CommandName="ShowAll" Text="Show All" />
<asp:Button ID="btnSearch" runat="server" CausesValidation="True" CommandName="Search" Text="Search" ValidationGroup="vldSearch" /><br />
<asp:TextBox ID="txtSearchName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="vldSearchName" runat="server" ErrorMessage="You have to provide an attorney name to search for." Text="*" ControlToValidate="txtSearchName" ValidationGroup="vldSearch" ForeColor="White"></asp:RequiredFieldValidator>
</HeaderTemplate>
In the Row Command event handler, here is how I am setting the visibility of the button:
If Not Me.dgAttorneys.HeaderRow Is Nothing Then
Dim btnShowAll As Button = Me.dgAttorneys.HeaderRow.FindControl("btnShowAll")
btnShowAll.Visible = Me.sqlAttorneys.SelectParameters.Count > 0
Trace.Write("Show all status is " & btnShowAll.Visible.ToString)
End If
The trace statement is showing the correct visible status - if the "show all" button is clicked, I do a SelectParameters.Clear() on the sqlAttorneys sqlDataSource.
Is my problem due to a misunderstanding of how the "FindControl" method works - I had assumed my new btnShowAll that I define is actually a reference to the "physical" control on the aspx page, so any changes I make to my local object is reflected in the control on the page.
If this is not the case, what is the best way to get a reference to the button control in the header row of the grid view?
I managed to get the button behavior to work - it was all to do with where in the overall process I was setting the button visibility. I moved that code block (setting the button visibility based on the presence of a search parameter) to the DataBound event for the data grid, and the button's visibility was set as it should be.
I suspect this is because during the overall data binding process, based on the state of the overall grid view and each grid row, the appropriate template object is used to render each row. Thus, any changes made to the button's visible property were being overridden during the data binding process. By shifting my code to set the visibility until after the data binding was complete, then it took effect.

Using Validation controls with a GridView

A typical situation:
In my GridView control, I have a Footer row which contains a Textbox and an "Add" Button. When the button is pushed, the Text entered in the TextBox is added to the grid. I also have a validation control to require that, when the button is pushed, that text has been entered in the TextBox. After a new row is added, the textbox is clear to allow for easy entry of the next item.
The user may also edit the text in previously entered rows by clicking the Edit LinkButton, which puts the row into edit mode. Clicking an Update LinkButton commits the change.
The problem:
When, I click the Update link to commit the changes, if text has not been entered in the Footer row's TextBox (the row used to add a new entry), the validation control returns a "Entry Required" error. It should only require an entry if the Add button is pushed, not if the Update LinkButton is pushed.
It seems that the server side Validation control's validating event fires before the GridView's RowCommand event or the btnAdd_Click event, so I am wondering how, from the server, I can determine what event fired the postback so I can determine whether what edits should be performed for the given situation.
I am using a mix of client side "required" validation edits as well as more complex server sides. Since I probably have to have some server sided validations, I would be happy with just knowing how to handle server sided validations, but really, know how to handle this situation for client validations would also be helpful.
Thanks.
Convert your CommandField into a TemplateField, and in the EditItemTemplate, change the Update LinkButton's CausesValidation property to false.
Update:
Converting to a TemplateField is simple and doesn't require any code changes (just markup):
Changing the CausesValidation property to false in the markup is also straightforward:
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CausesValidation="False"
CommandName="Update" Text="Update"></asp:LinkButton>
<%--
More controls
--%>
</EditItemTemplate>
<ItemTemplate>
<%--
Controls
--%>
</ItemTemplate>
</asp:TemplateField>
Now, if you want your footer and data rows to be validated separately, you need to use validation groups, which is explained in Microsoft's documentation. All the controls in the same validation group will have their ValidationGroup property set to the same value, like this:
<asp:LinkButton ID="lnkUpdate" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" ValidationGroup="GridViewDataRowGroup">
</asp:LinkButton>

How to get value in a textbox that is readonly

I have a textbox.In its onclick iam calling a javascript fn to call calendar.Texbox is readonly. Clicking on textbox calendar is coming and value is showing in textbox. But on clicking submit button where I have written code to save, there i am not getting value in textbox. What may be the reason for that?
I suspect that your text box has the disabled attribute instead of readonly which prevents it from posting its value to the server.
I had this problem too, there is a really simple workaround
Instead of making the textbox ReadOnly using properties option. Do it thru the code behind adding this code:
YourTextBox.Attributes.Add("readonly", "readonly");
You can get the value by using
Request.Form[YourTextBox.UniqueID]
I'm guessing the textbox is disabled so that people have to use the calendar control to enter a date? The textbox is just for showing the selected date?
If you want the textbox to stay readonly (i.e. disabled client-side), have a hidden input that has the value you want to handle on the server is the way to go probably. So add an additional input for to the page. Use
<asp:HiddenField ... runat="server" />
So the client-side code that updates your readonly textbox will also update your hidden input.
if readonly property is true, its not break your .cs call. you can use this as always:
here are your inputs:
<asp:TextBox ID="txtBraid" runat="server" Text="Im sooo readonly" ReadOnly="True"></asp:TextBox>
<asp:Label ID="lblBraid" runat="server" Text="Im gonna change, i promise"></asp:Label>
on .cs page put these to onClick function or something:
lblBraid.Text = txtBraid.Text;

How do I add an empty first entry do an <asp:DropDownList>?

I have a dropdown, I have a datasource, I have AutoPostBack set to true.
I want to add a first entry to the datasource that says something like "--- select country ---" and selecting this entry won't cause postback.
This feels like it should be easy to do, yet I can't seem to be able to find a good solution.
Thanks.
In your aspx page (the important part is handling the DataBound event and setting CausesValidation="true" to force validation of a drop down list):
<asp:DropDownList ID="ddlCountries" runat="server" DataSourceID="dsCountries" AutoPostBack="true" OnDataBound="ddlCountries_DataBound" CausesValidation="true" />
<asp:RequiredFieldValidator ID="rfvCountries" runat="server" ControlToValidate="ddlCountries" Display="Dynamic" ErrorMessage="Please select a country." />
In your codebehind (it is important that the value of the inserted item is String.Empty for the required field validator to work!):
protected void ddlCountries_DataBound(Object sender, EventArgs e)
{
ddlCountries.Items.Insert(0, new ListItem("--- select country ---", String.Empty));
}
Note: If you don't want the validator's message to display, set the "Display" property to "None".
You can also add the row manually through the designer but you have to make sure that the DropDownList's property AppendDataBoundItems = True as well so that the databound rows are tacked onto the first row.
Previous answers deal with inserting the value, but I understand your problem is the AutoPostBack property. I suppose you dont want to postback that value and that's your problem, am I right?
Maybe there's a better solution, but I'd suggest not using AutoPostBack. You could handle postback automatically using the selected value change event.
IMHO if the AutoPostBack does not work as you want, it's always better to implement your own solution that to put some kind of "patch" over it to "fix" it.
Hope that helps
Use the insert method as others have suggested to add the item at index 0 with a value to indicate not selected ( for example 'unknown'). Then use validators, add a required field validator and set the InitialValue property to the value of the new list item ('unknown' in our example).
Set index 0 to be the selected item on page load and if not postback.
If the user doesn't select another option the validator will prevent the postback.
Hope that's what you are looking for.

Resources