Validating Entries in an ASP.NET GridView without JavaScript - c#

Background
I have a GridView where input in Column1 depends on the input Column2.
If a user enters a N in Column2 the system will put a Y in Column1.
The Validatons are implemented using Regexs and Custom validation. I would prefer a validation solution that doesn't use JavaScript.
|Column1| Column2|
__________________
| Y | N
__________________
|N | Y
__________________
|N | N
Question
How can I validate these entries in the Gridview without using JavaScript?

Why not use two radio buttons?
<asp:templatefield>
<itemtemplate>
<asp:radiobutton id="rbYes" runat="server" groupname="YesNo" text="Yes" />
<asp:radiobutton id="rbNo" runat="server" groupname="YesNo" text="No" />
</itemtemplate>
</asp:templatefield>

You could use radio buttons and the 'Template' column feature of a GridView. The GridView markup would look like this:
<asp:GridView ID="gvTest" runat="server" AutoGenerateColumns="false"
OnRowDataBound="gvTest_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Column 1">
<ItemTemplate>
<asp:RadioButton ID="rbSelect1" runat="server" Text="" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Column 2">
<ItemTemplate>
<asp:RadioButton ID="rbSelect2" runat="server" Text="" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The trick then would be to correctly set the 'GroupName' property of each radio button so that each row of the resulting grid is treated as a single radio button group by the browser. That's where the 'OnRowDataBound' handler specified on the grid comes into play. The definition of the 'gvTest_RowDataBound' handler method could be something like:
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
RadioButton rb1 = (RadioButton)e.Row.FindControl("rbSelect1");
RadioButton rb2 = (RadioButton)e.Row.FindControl("rbSelect2");
rb1.GroupName = rb2.GroupName = string.Format("Select_{0}", e.Row.RowIndex);
}
}
By appending the row index to the group name to both of the radio buttons in each row you're going to ensure that the browser will treat them as a group and only allow the selection of one value per row. The result would look something like this:

Related

I have to click the update button twice and the first time all values in the cells of the Gridview disappear

I have a Gridview set up and populated by binding my data. I have created a column that holds an "Edit" button. Clicking that button changes all of my fields to a text box populated with the data that is pulled from the database and replaces the "Edit" button with an "Update" and "Cancel" button. Up to this point all is working as intended. I change the value in the textboxes that I want to update and click the "Update" button. At this point everything is cleared out of all of the text boxes in each cell. I can enter the data again at this point and click the "Update" button a second time and any values that I have entered (the second time) will be passed back to my updating event procedure, but that is not quite the functionality I'm looking for.
I have run across a couple reports of the "Edit" button requiring 2 clicks to function, but the fixes didn't really apply to my situation.
This is my page_load
{
if (!this.IsPostBack)
{
Build_DDL();
Build_Turn_Checkbox_List();
Show_Data();
}
CheckBox_Selected_Values();
}
This is my gridview declaration:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" HeaderStyle-CssClass="headerClass" HeaderStyle-VerticalAlign="Bottom"
RowStyle-Wrap="true" HeaderStyle-Wrap="true" OnDataBound ="OnDataBound" AllowSorting="True" HeaderStyle-Height="50px"
OnSorting="GridView1_SelectedIndexChanged" CssClass="reportData" OnRowDataBound="GridView_OnRowDataBound"
OnRowCancelingEdit="GridView1_RowCancelEdit" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<HeaderStyle VerticalAlign="Bottom" Wrap="True" Height="50px" />
<RowStyle Wrap="True" CssClass="oddRow" />
<AlternatingRowStyle CssClass="evenRow" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID ="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State" Visible="false">
<ItemTemplate>
<asp:Label ID="lbl_state" runat="server" Text='<%#Eval("STATE") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_state" runat="server" Text='<%#Eval("STATE") %>'></asp:TextBox>
</EditItemTemplate>
There are more fields, but they are all built exactly the same.
Here is my update code:
{
//declare variables
string stateVal;
//set up textboxes
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox txt_State = (TextBox)row.FindControl("txt_state");
stateVal = txt_State.Text;
}
I didn't notice that when I clicked the "Edit" button on row 2, it was row 5 that was transitioning into text boxes. This was because I have the following code creating groupings in the gridview and each group creates a new row that is not accounted for in the row index scheme:
helper.RegisterGroup("State", true, true);
helper.RegisterGroup("Project Type", true, true);
helper.GroupHeader += new GroupEvent(Helper_GroupHeader);
helper.ApplyGroupSort();
GridView1.DataBind();
I will have to somehow account for the group headers and adjust the neweditindex accordingly.

asp.net template field get cell text using find control doesn't work

I know that this question was asked many times before but I couldn't find an answer which solves my problem.
I need to do something very basic and simple, I have a GridView which has a template field and I am trying to access a cell text in the GridView,
So I have tried the following:
C#
Label lbl = GridView1.SelectedRow.Cells[0].FindControl("lblSomething") as Label;
string customerName = lbl.Text;
html
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:TemplateField SortExpression="Item">
<HeaderTemplate>
<asp:LinkButton ID="lblSomething" runat="server" Text="title" CommandName="Sort" CommandArgument="Something" ForeColor="white"></asp:LinkButton><br />
<asp:TextBox runat="server" ID="Something" AutoPostBack="false" Width ="60" autocomplete="off"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%#Eval("Something") %>
</ItemTemplate>
<ItemStyle Width="80px" />
</asp:TemplateField>
lbl returns null.
Can someone please explain to me how to use FindControl? Try to be as clear as you can.
Your LinkButton is in the HeaderRow, not a normal row. You need to use FindControl on the header.
LinkButton lb = GridView1.HeaderRow.FindControl("lblSomething") as LinkButton;
And make sure you cast the right type. You are searching for a Label, but lblSomething is a LinkButton.

Add different Buttons on a single column of a GridView

I've added an Edit button to the Action column of my Gridview using a TemplateField. I want every column to have the edit button in the first column except for the last row, which should have an Add button there instead. How would I implement this separate last row with the different button? Here is the code I have.
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="Edit" runat="server" text="Edit" OnClientClick="btnEditClick()" />
</ItemTemplate>
</asp:TemplateField>
DataTable dt = new DataTable();
dt.Columns.Add("Action");
DataRow row1 = dt.NewRow();
...
dt.Rows.Add(row1);
gridRoles.DataSource = dt;
gridRoles.DataBind();
First you have to add 2 button 1st Edit(visible) and 2nd Add (make it display=none initially)
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="Edit" runat="server" text="Edit" OnClientClick="btnEditClick()" />
<asp:Button ID="Edit" runat="server" text="Edit" OnClientClick="AddClick()" />
</ItemTemplate>
</asp:TemplateField>
Then Find Gridview Last row and find the Button Controls
GridViewRow row = GridView1.Rows[GridView1.Rows.Count-1];
Button Edit = ((Button)row.FindControl("btnedit")).Text;
Button Add = ((Button)row.FindControl("btnadd")).Text;
Edit.visible =false;
Add.Visible =true;
Here reverse the button display option : False for Edit and true for Add
That item template column is going to add whatever it's contents are to every row. One way around this is to add and empty column, and add your button during the OnRowDataBound event.
You can check to see if you are on the last row, and if so, add the other button, rather than the edit button.
One way to do it is to use the footer as the last line of the GridView. It could look like this:
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" ... >
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" text="Edit" OnClientClick="btnEditClick()" />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" text="Add" OnClientClick="btnAddClick()" />
</FooterTemplate>
</asp:TemplateField>
....
</asp:GridView>
You can look at this article for a complete example, with input controls and validation: Inserting a New Record from the GridView's Footer.

Update Gridview with data from radio button list on button click

Good Day!
I'm having a hard time with my Gridview. I'm using C#.net and sql server. I want to update my gridview rows with the data from the column of radio button list with a button outside gridview. Here's my gridview;
I want to update column[rating] with the selected value from radio button list on a single button click.
Currently, I update the gridview column rating by clicking the rate button and getting the rating value from the dropdown list above the gridview.
Now, I'm wondering if there's a way to do it on one click and get it's value from the radio button list inside the gridview. My gridview code is here;
<p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" onrowcommand="delete_enroll"
DataSourceID="training" Width="826px" AllowPaging="True" Visible="False"
style="text-align: center">
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="deleterow" Text="CANCEL" />
<asp:ButtonField ButtonType="Button" CommandName="RATE" Text="RATE" />
<asp:BoundField DataField="Training_id" HeaderText="Training_id"
SortExpression="Training_id" />
<asp:BoundField DataField="User_id" HeaderText="User_id"
SortExpression="User_id" />
<asp:BoundField DataField="User_name" HeaderText="User_name"
SortExpression="User_name" />
<asp:BoundField DataField="Date_enrolled" HeaderText="Date_enrolled"
SortExpression="Date_enrolled" />
<asp:BoundField DataField="Rating" HeaderText="Rating"
SortExpression="Rating" />
<asp:TemplateField HeaderText="Rate">
<ItemTemplate>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Text="Passed" Value="Passed"></asp:ListItem>
<asp:ListItem Text="Failed" Value="Failed"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</p>
Any help would be appreciated. Thanks!
You can loop through the rows of gridview in you button click event handler and update the respective row like this:-
protected void btnUpdate_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
RadioButtonList RadioButtonList1 = row.FindControl("RadioButto nList1")
as RadioButtonList;
row.Cells[6].Text = RadioButtonList1.SelectedValue;
}
}

Adding cells in GridView

How can i add cell in specific column for each row in gridview,i want to use RowCreated Events.
i have gridview that has 3 columns (ProductName, Price, Count) i get (ProductName, Price) from database, and i want to add value for (count), ex: (Kitkat, 2$ ) i want to add number 5 to (count) column, i want to handle this operation when each row created.
Thanks
Since you haven't shown your markup, I'm going to assume (based on your comment) that the first two columns are <BoundFields>. If that's the case, I would add a third column as a <TemplateField>, place a Label in it, and use the RowDataBound event to add the correct number to the Label.
Here is what the markup would look like:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="Price" HeaderText="Price" />
<asp:TemplateField HeaderText="Count">
<ItemTemplate>
<asp:Label ID="countLbl" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code-behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Label countLbl = (Label)e.Row.FindControl("countLbl");
//Your logic for what number to use should go here, I'm just defaulting to 5.
countLbl.Text = "5";
}

Categories