Attaching Changed Event to Dynamically Created Radiobuttons - asp.net

I'm dynamically creating a load of radiobuttons in code behind (vb.net on load) and am wondering how I should create the events on them. I have a gridview with two columns and each row has a radiobutton in both columns that are in a group together (fyi group means check one, the other is unchecked). I want to change the background colour to yellow on whichever one is checked. How best would I do this? Javascript (catch all radio button change events), JQuery (catch all radio button change events) or Vb.net (attach method on creation)? Here is how I'm creating them;
Dim r As RadioButton
Dim l As Label
Dim radioBtnNumber As Integer = 0
For row As Integer = 0 To GridView1.Rows.Count - 1
If GridView1.Rows(row).RowType = DataControlRowType.DataRow Then
Dim x As Integer = 0
For Each tc As TableCell In GridView1.Rows(row).Cells
l = New Label()
l.Text = tc.Text
If (x = 1) Or (x = 2) Then
r = New RadioButton()
r.GroupName = String.Format("RdBtnGroup{0}", row)
r.ID = radioBtnNumber.ToString
//Could add in event here. Tried this but didn't work
//r.Attributes.Add("OnCheckedChanged", "radiobuttonChecked()")
tc.Controls.Add(r)
radioBtnNumber = radioBtnNumber + 1
End If
tc.Controls.Add(l)
x = x + 1
Next
End If
Next
That code is actually more confusing that it should be because the gridview is actually flipped (veritical as opposed horizontal). So I have radiobuttons named 0, 1, 2, 3, 4 etc with 0 and 1 in a group, 2 and 3 in a group etc and I just want to catch which one has been changed. Bear in mind though that I need the name of the RB or it's position in my gridView as I'll have to change the background colour of the RB it's paired with also!

Add line (code is C#, translate to VB):
r.CheckedChanged += new System.EventHandler(this.radiobuttonChecked);
when you create the RadioButton. radiobuttonChecked should be method of your webpage:
protected void radiobuttonChecked(Object sender, EventArgs e)
{
...
}
where you will be able to cast sender to RadioButton and analyze its properties. This will cause a postback to the server, where you can modify the radio buttons.
If you want to do it on the client, then you can first assign CssClass (e.g. "rbClass") to the same string for all of them and also use
r.Attributes.Add("pairName", "<name for the pair of radiobuttons>")
Then add javascript to your page:
$(document).ready(function(){
$(".rbClass").change(function(){
// here you look at $(this).attr and
// adjust its and its pair's css accordingly
})
});

Related

ASP.Net GridView Edit/Update/Cancel/Delete Events On RowClick

We've got an ASP.Net application that contains a GridView Control that contains row edit functionality.
This allows a user to Edit, Delete, Or Cancel editing on a particular row.
For Example Read Only Mode Looks Like This:
And Edit Mode Looks Like this:
The mechanism that allows the user to enter Edit mode is based on an Edit Button in a template column that changes the selected row from a read only row to an editable row using a RowEditing event something like this:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = e.NewEditIndex;
ReBindDataGrid();
}
Canceling is pretty much the opposite where we have a button click event that changes the row back to ready only mode:
protected void grdOfMine_RowEditing(object sender, GridViewEditEventArgs e)
{
grdOfMine.EditIndex = -1;
ReBindDataGrid();
}
(Apologies to those who are already familiar with this aspect of ASP.Net forms development.)
We've also created a footer row that allows a user to add a new row:
We're looking for a way to extend the ASP.Net GridView control do this without using the buttons to fire the events.
For example:
Allow a user to enter edit mode for a row, by clicking in a cell of any given row and update the selected record say, on an Enter keyboard input event (Instead of the Edit Button).
Delete a record say, on a delete keyboard input event (Instead of the Delete Button).
Add a record in a similar fashion (Instead of the Add Button).
We were attempting this functionality using Infragistics controls, however we had a very tough time getting these to work, so we decided not to use them.
Thanks in advance
I am working on asp.net gridview on webforms and using Gridview RowCommand method of GridView OnRowCommand event for the Buttons View, Edit & Update inside TemplateField.
if (e.CommandName == "EditContract") {
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;
gvContract.SelectRow(rowIndex);
using (SqlCommand cmd = new SqlCommand("spContractEdit", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RoleName", SqlDbType.Char).Value = Session["RoleName"];
cmd.Parameters.Add("#UnitName", SqlDbType.Char).Value = Session["UnitName"];
cmd.Parameters.Add("#ContrSerialNo", SqlDbType.Int).Value = SerialNo;
dAdapter = new SqlDataAdapter(cmd);
DataTable DtContract = new DataTable();
dAdapter.Fill(DtContract);
}
if (e.CommandName == "UpdateContract") {
lblMessage.Text = "";
lblFile.Text = "";
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int SerialNo = (int)gvContract.DataKeys[row.RowIndex].Value;
using (SqlCommand cmd = new SqlCommand("spContractUpdate", myObj.DbConnect()))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ContrNewRev", SqlDbType.VarChar).Value = ddNewOrRevised.SelectedValue;
cmd.Parameters.Add("#ContractTitle", SqlDbType.VarChar).Value = txtContractTitle.Text;
cmd.Parameters.Add("#FinancerID", SqlDbType.Int).Value = ddFinancer.SelectedValue;
}
This code is working fine when the page loads first time but has 2 problems after that. i.e. 1. It is editing and updating data when the page gets load for the first time but when I try to edit the same row or any other then it doesn't. I know it is because I have defined the !Page.IsPostback method on the Page_Load event but I do not know how to tackle this situation. 2. Problem is How to restrict the gridview row to update only that data whose row is selected?
Please suggest me a solution.
GridView Sample

Button in DetailRow needs the keys from the two upper nested APSxGridViews

I do have two nested APSxGridView objects. The DetailRow in the inner one contains also a button. I want to initialize the button so that it launches new window in the browser. For that, I need the key id's from the upper GridViews.
GridView1
GridView2
DetailRow
Button
I already know how to get the key from the GridView2 -- my existing code looks like:
protected void btnModify_Init(object sender, EventArgs e)
{
ASPxButton btn = sender as ASPxButton;
GridViewDetailRowTemplateContainer clsdetail = btn.Parent as GridViewDetailRowTemplateContainer;
string partition = "1"; // this should be filled with the GridView1 id
string cls = clsdetail.KeyValue.ToString(); // this is the GridView2 id
// The following code just uses the information.
string panelid = "t" + partition + "-" + cls;
btn.ClientSideEvents.Click =
String.Format("function(s, e){{ window.open('producttag.aspx?partition={0}&cls={1}','{2}'); }}",
partition, cls, panelid);
}
Notice the string cls = ... that gets the key from the inner grid (the button is inside its detail row).
How can I get the key for the outer gridview? Can I do it through parents again? Or is there any other way?
Update: More than one detail row can be expanded in the inner grid view. This way, I cannot pass the id's through some hidden element. I need to get it being at the button level from the upper objects.
OK. I have found it -- use NamingContainer:
ASPxButton btn = sender as ASPxButton;
GridViewDetailRowTemplateContainer clsdetail = btn.NamingContainer as GridViewDetailRowTemplateContainer;
Control gvClasses = clsdetail.Grid; // the grid 2
Debug.Assert(gvClasses.ClientID.EndsWith("gvClasses"));
GridViewDetailRowTemplateContainer partitionsdetail = gvClasses.NamingContainer as GridViewDetailRowTemplateContainer;
// the upper is the detail row of the grid 1
string partition = partitionsdetail.KeyValue.ToString(); // from grid 1
string cls = clsdetail.KeyValue.ToString(); // from grid 2

alternate color gridview rows based on change of cell value asp.net

1 item
1 item
2 item
2 item
3 item
4 item
4 item
5 item
I have a gridview bound to a datasource. I want to change the color of the rows based on the GROUPING of the first column. I do not know what the values of the column will be, but basically I need to switch from one color to the other color when the value in that column changes. (I used bold to show what I mean) Once again I don't know the value in that column, so I can't just say "if it equals 1 then do this" - I know how to do that. :)) So just switch the row color from blue to red each time the value in column one changes. (i.e. red, red, blue, blue, red, blue, blue, red per the example above) Thanks for any suggestions. (I'm a VB person, but can manage to translate code if need be. Thanks again)
I found the following (cept in C#, but here it is in VB) This works. :) I can setup the css for the two classes and works out fine. Every time the item in column 1 changes it changes the class on the row.
Dim currentClass As String = "alternateDataRow"
Dim currentGroup As String = ""
Protected Sub gvPayrollRecords_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gvPayrollRecords.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim rowGroup As String = e.Row.Cells(1).Text
If rowGroup <> currentGroup Then
If currentClass = "datarow" Then
currentClass = "alternateDataRow"
Else
currentClass = "datarow"
End If
currentGroup = rowGroup
End If
e.Row.CssClass = currentClass
End If
End Sub

How to modify property of radiobutton without using its id tag

I need to go through a loop and check the proper radiobutton. I have multiple radio button named rb with a color such as "rbGreen, rbRed, rbYellow..."
Here is my code behind: (listColors is a list of strings)
Private Sub selectColor(color As String)
Dim i As Integer
For i = 0 To listColors.Count - 1
If listColors(i) = color Then
Dim rb As RadioButton = TryCast(Page.FindControl("rb" & color), RadioButton)
rb.Checked = True
End If
Next i
End Sub
While debugging, I got an error because rb is nothing...
My guess is that the RadioButtons in question are not actually part of the Page, and are instead part of a UserControl or template based control (such as a Repeater).
If so, then you need to modify your code to use the FindControl of the control that holds the RadioButtons in question.
If this is within a UserControl the easiest thing to do is something like...
Me.FindControl("rb" & color)

Adding hyperlinks dynamically by code

I have a web form but I have to do this by code since I dont know the number of hyperlinks I need from the beginning.
How can I add some hyperlinks with Image in a label, the number of hyperlink depends on the number of rows of a query, and each row give me the link information to navigate.
Thanks in advance.
As you loop through your data you can manually add a link to the row something like this:
For i As Integer = 0 To 10
Dim row As New HtmlTableRow
row.Cells.Add(New HtmlTableCell)
Dim Link As New HyperLink
Link.Text = "WhateverText"
Link.NavigateUrl = "page.aspx"
Link.ImageUrl = "~/Theme/Images/SomeImage.gif"
Link.ToolTip = "ToolTipText"
row.Cells(0).Controls.Add(Link)
Next
That of course adds the link as the first cell in an html table. Not sure how you plan to display your data.
In response to the comment below. You can instead insert the new cell something like this
For i As Integer = 0 To 10
Dim row As New HtmlTableRow
Dim cell As New HtmlTableCell
row.Cells.Insert(1, cell)
Dim Link As New HyperLink
Link.Text = "WhateverText"
Link.NavigateUrl = "page.aspx"
Link.ImageUrl = "~/Theme/Images/SomeImage.gif"
Link.ToolTip = "ToolTipText"
row.Cells(0).Controls.Add(Link)
Next
You could also simply add the control to the existing cell that the label is in instead of making a new cell. You can do that by the index value of your existing cell (starting at 0 for each cell that is in the row)
This question is similar to what you want to do:
Auto increment asp control ID
Two options either use a repeater or dynamically add the controls to a panel or some other container control.

Resources