Required Field validator in grid view - asp.net

I have one dynamic grid. In that amount and date are not null columns.
<asp:TemplateField>
<ItemTemplate>
<asp:RequiredFieldValidator ID="reqAmount" runat="server"
ControlToValidate="txtAmount" Display="None" InitialValue=""
Visible="true" ValidationGroup="req" SetFocusOnError="true">
</asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
The user should enter something in the specified columns. My issue is that if the save button is pressed the required validator is firing for all the rows that are empty. It should only show if the user is in the current row. If the user leaves the particular row empty and presses the save button the error message should show in the current row, not all the rows.
How do I do this?

You can find what you are looking for at
GridView Examples for ASP.NET 2.0: Editing the Underlying Data in a GridView

Related

Can't access checkbox values in gridview on postback

This sounds a lot like a bunch of other questions on here, but nothing I've read follows what I'm seeing.
I have a gridview that contains a number of bound fields and a couple of template fields containing checkboxes. The gridview is bound to a custom datasource on pageload (inside a "not page.ispostback()" condition). The user can check the checkboxes to specify certain actions that are then committed when a link button is clicked.
The link button's click event has the following code in it:
For Each row As GridViewRow In UnpaidEntriesGridView.Rows
Dim paidCheckbox As CheckBox = CType(row.FindControl("PaidCheckbox"), CheckBox)
If paidCheckbox.Checked Then
// perform database action
End If
Next
Initialise() // (this rebinds the gridview)
No matter what I do, I cannot get hold of the checked value of any checkbox in the gridview that the user has changed. All checkboxes remain in their original state (set on data bind).
This is more than likely a page life-cycle issue, but for the life of me, I can't figure out why the user's changes aren't persisted after postback, despite the fact that the gridview isn't rebound until after I've checked.
ViewState is enabled, everything's pretty standard here otherwise.
Gridview code snippet from ascx follows:
<asp:GridView ID="UnpaidEntriesGridView" runat="server" AutoGenerateColumns="false" EnableViewState="true">
<Columns>
<asp:BoundField HeaderText="Entry Name" DataField="EntryName" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="PaidCheckbox" runat="server" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinkButton ID="UnpaidEntriesSaveLinkButton" runat="server" Text="Commit Changes" />
Any help (even a slap for being so stupid) would be massively appreciated.

Set a DropDownList SelectedValue to a bound field with sometimes null value

I have a situation where I have a gridview which is populated from a sql table which editing is allowed. For one of the fields, I have it so the user has to select a value from a drop down box in the edit template for the gridview.
<asp:TemplateField HeaderText="Department" SortExpression="Department">
<EditItemTemplate>
<asp:DropDownList ID="ddlEditDepartment" runat="server"
SelectedValue='<%# Bind("Department") %>'>
<asp:ListItem>Department 1</asp:ListItem>
<asp:ListItem>Department 2</asp:ListItem>
<asp:ListItem>Department 3</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
If you select "edit" for a record in which this field already has a value stored in the table for it, no problem. However, if you select "edit" and there is no value in the table for it yet, you get the following error
'ddlEditDepartment' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
How can I account for blank or null values in this situation and make this work?
You're binding your DropDownList to a field named "Department" in your GridView's datasource:
SelectedValue='<%# Bind("Department") %>'
It's kind of a hack, but you could modify the query that populates the Department field of your GridView to account for the nulls (by coalescing them out):
SELECT COALESCE(Department, "No department entered") AS Department
FROM YourTable
And then just add that as kind of a "default" option in your dropdown:
<asp:ListItem>No department entered</asp:ListItem>
It sounds like you are trying to update a record that does not exist. So, you have a few options, depending on what you want to do. You could capture the error and display a user friendly alert to the user that they need to create a new record before editing. Or, you could capture the error and run an insert command if the error gets raised. Or you could prevent the error from firing all together. This would be my suggestion. In your code behind, when the dropdowlist event fires, take the ID and run a query to see if the record exists. If it does, update it. If not, either alert the user or you could just do the insert then. If you have a specific question on how to do this, let me know.

Multiple databound controls in a single GridView column

I have a grid view that is data bound to a dataset. In a grid I have a column DefaultValue, which has three controls in it - a dropdownlist, a checkbox and a textbox. Depending on the data that is coming in it can switch to any of these controls. Everything is simple enough when we need just to display data - in gridview_prerender event I simply make one of the controls visible. The control is setup like following:
<asp:TemplateField HeaderText="Default Value" SortExpression="DefaultValue">
<ItemTemplate>
<asp:TextBox ID="txt_defaultValue_view" runat="server" Text='<%# Bind("DefaultValue") %>' Enabled ="false" />
<asp:DropDownList ID="ddl_defaultValue_view" runat="server" Enabled ="false" />
<asp:CheckBox ID="chk_defaultValue_view" runat="server" Enabled ="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_defaultValue_edit" runat="server" Text='<%# Bind("DefaultValue") %>'/>
<asp:DropDownList ID="ddl_defaultValue_edit" runat="server" />
<asp:CheckBox ID="chk_defaultValue_edit" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
My problem starts when I am in edit mode and I need to update the grid with new data. Since only the textbox control is databound, the RowUpdating event can only access data from the textbox column and all of my other data simply gets discarded. I also can't databind with checkbox and dropdownlist control, since they can get an invalid data type exception. So, does anyone know how can I update a column that has three different controls, where each of these three controls might have a valid data?
Thanks
First, i would switch visibility of the controls in RowDataBound of the Grid and not on PreRender, because it can only change on DataBinding and not on every postback.
You can there also bind the Dropdown to its datasource, change the checked-state of the Checkbox and set the Text-property of the Textbox according to the the Dataitem of the Row.
When you update you can find your controls with FindControl in RowUpdating and get their values(f.e. Dropdownlist.SelectedValue).
GridView has pair of events:
RowUpdating/RowUpdated
RowDeleting/RowDeleted
....
In your case your need RowUpdating - is called right before update is performed, So find in row expected control (saying checkbox) and make preparation before pass to database
As another way review possibility to use ObjectDataSource event Updating - it is usual way to specify parameters for query execution.

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 show insert or cancel buttons instead of links with Detailsview?

How to show insert or cancel buttons instead of links with Detailsview?
You can use the CommandField inside your <fields> tag
<Fields>
<asp:CommandField ButtonType="Button" />
</Fields>
Came across this question while looking for other information on the DetailsView. An alternative approach to that above is to change the commandfield into a template field (from the Edit Fields dialog box for the details view, select the command field entry in the list of selected fields, then click on the "Convert this field into a template field" link). Then, back in your source view, you will see something like this:
<asp:TemplateField HeaderText="Actions">
<InsertItemTemplate>
<asp:ImageButton ID="btnInsertAccept" runat="server" CausesValidation="True" CommandName="Insert" AlternateText="Insert" ImageUrl="images/16x16.check.gif" ToolTip="Click to insert this new division." ValidationGroup="ValidationInsert" />
<asp:ImageButton ID="btnInsertCancel" runat="server" CausesValidation="False" CommandName="Cancel" AlternateText="Cancel" ImageUrl="images/cancel.png" ToolTip="Click to cancel inserting this new division." />
</InsertItemTemplate>
</asp:TemplateField>
Now, there will also be ItemTemplate and EditItemTemplate entries, but you get the idea. Ive changed the default asp:LinkButton controls to ImageButtons, but you could also use normal buttons, whatever fits your UI design. The important part is the CommandName entry on each control - be it insert, Update, Delete, Cancel - it is that command name that causes the appropriate operation to take place.
Hope that give you additional help.

Resources