Add dynamic radio button object to GridView - asp.net

I need to add a custom radio button control that I created based on an if condition to my GridView. My radiobutton will be enabled or disabled based on this condition and will have the text
changed as well.
I'm trying to figure out how to add a radiobutton object into my data row instead of a string dt.Columns.Add("FirstName").
<telerik:RadGrid runat="server" ID="grd1" OnNeedDataSource="grd1_NeedDataSource">
<MasterTableView AutoGenerateColumns="False">
<Columns>
<telerik:GridTemplateColumn HeaderText="Radiobutton header" UniqueName="col1">
<ItemTemplate>
<asp:RadioButton ID="rbType" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "rbEnableorDisable")%>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="FirstName header" UniqueName="col2">
<ItemTemplate>
<asp:Label Text='<%# DataBinder.Eval(Container.DataItem, "Name")%>' runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
CodeBehind
Private dt As DataTable
Private dr As DataRow
dt= New DataTable
dt.Columns.Add("rbEnableorDisable")
dt.Columns.Add("FirstName")
Dim rb As RadioButton
rb = New RadioButton
For each item in itemlist //some data iteration declared elsewhere
dr = dt.NewRow()
If (Condition)
rb.Text = "Should be Disabled"
rb.Enabled = False
Else
rb.Text = "Should be Enabled"
rb.Enabled = True
End if
dr.Item("FirstName") = item.FirstName
dr.Item("rbEnableOrDisable") = rb//?Code for inserting a radio button object
dt.Rows.Add(dr)
Next
With grd1
.DataSource = dt
.DataBind()
End With
So far with this code
I am only able to display the radiobutton text if i have dr.Item("rbEnableOrDisable") = rb.Text.
I need to display the whole radiobutton object(show the text and if it's enabled or disabled among others)
I tried
LocationData.Columns.Add(New DataColumn("rbType", GetType(RadioButton)))
but it seems I need to append to the ItemTemplate
Also tried adding the whole column dynamic with:
grd1.Controls.Add(rb)

You need to have something in your DataItem to put the radiobutton enabled or disabled and assigment to Enabled property.
Enabled='<%# DataBinder.Eval(Container.DataItem, "booleanData")%>'
If you need to put RadioButton checked or unchecked use Checked property.

Related

Explicit iteration in Gridview and using findControl returns Nothing

I am trying to loop through GridView control. It contains radio button and I would like to set it's checked property based on certain condition. However, the findControl method returns nothing.
Here is the aspx code:
<asp:GridView ID="GridViewInfo"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="Result_ID">
<Columns>
<asp:TemplateField HeaderStyle-Width="3%" HeaderText="SELECT">
<ItemTemplate>
<input name="RadioButtonResultID"
id="RadioButtonResultID" type="radio"
value='<%# Eval("Result_ID") %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Characteristics"
DataField="Characteristics" />
</Columns>
</asp:GridView>
Code behind:
Private Sub HighlightSelectedRow(ByVal id As String)
Dim rowCount As Int32 = 0
For Each row As GridViewRow In GridViewLabInfo.Rows
If (GridViewLabInfo.DataKeys(rowCount).Value.ToString() = id) Then
row.CssClass = "SelectedRowStyle"
'Both of the below lines are failing
TryCast(row.FindControl("RadioButtonResultID"), RadioButton).Checked = True
CType(row.FindControl("RadioButtonResultID"), RadioButton).Checked = True
End If
rowCount = rowCount + 1
Next
End Sub
You cast is wrong. That is not a asp.net radio button (RadioButton), but is a HTML one,
So your cast in in this case should be:
TryCast(row.FindControl("RadioButtonResultID"), HtmlInputRadioButton ).Checked = True
And you don't even need the cast, but this should work:
Dim MyRadioBut As HtmlInputRadioButton = row.FindControl("RadioButtonResultID")
MyRadioBut.Checked = True
However, in BOTH of the above cases? You can't pick up the control in code behind unless you state that control is rendered by the server.
You need to add the runat="server".
eg this:
<input name="RadioButtonResultID"
id="RadioButtonResultID" type="radio"
value='<%# Eval("Result_ID") %>' runat="server" />

How to read the data of the row when clicked the button in the same row

I have the data displayed in the grid as follows:
StartDate Enddate Button
16/3/2013 17/3/2013 Signup---> this is an ASP button
18/3/2013 19/3/2012 Signup----> this is an ASP button
20/3/2012 20/3/2012 Signup----> this is an ASP button
I want asp.net with c# code when i clicked on first row signup button i want to get the data of the first row. If clicked on second row i want only the data of the second row startdate and end time. How can i acheive this? Please hep me in this regard.
In the asp button, Set properties: CommandName="SignUp" CommandArgument='<%# Container.DataItemIndex%>'
Now, when this button is clicked it calls Gridview's RowCommand Event
In that event e.CommandArgument contains your Row Number.
GridViewRow gvr= gvLinkImages.Rows[e.CommandArgument];
Now you can use gvr.Cells[column number] to get the particular text (Not recommended)
or use findcontrol to get the label or literal of the start/end date( assuming you are using Templatefields)
Sample code below
C#
protected void gvResults_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignUp")
{
int rwNumber = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvResults.Rows(rwNumber);
System.DateTime rowStartDate = default(System.DateTime);
System.DateTime rowEndDate = default(System.DateTime);
//If you are using Templatefields
Literal lblRowStartDate = gvr.FindControl("lblStartDate") as Literal;
Literal lblRowEndDate = gvr.FindControl("lblEndDate") as Literal;
rowStartDate = Convert.ToDateTime(lblRowStartDate.Text);
rowEndDate = Convert.ToDateTime(lblRowEndDate.Text);
//Incase you are not using TemplateFields or Autobinding your grid
rowStartDate = Convert.ToDateTime(gvr.Cells[0].Text);
rowEndDate = Convert.ToDateTime(gvr.Cells[1].Text);
}
}
ASPX
<asp:GridView runat="server" ID="gvResults" AutoGenerateColumns="false" OnRowCommand="gvResults_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal runat="server" ID="lblStartDate" Text='<%#Container.DataItem.StartDate%>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal runat="server" ID="lblStartDate" Text='<%#Container.DataItem.EndDate%>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="btnSignUp" CommandName="SignUp" CommandArgument="<%# Container.DataItemIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Make checkbox of detailsview to be checked by default for insert new record?

I am using DetailsView which its DefaultMode: insert, and I want to make its checkbox to be checked by default also user can change it to unchecked, but to bind checkbox we should use
Checked='<%# Bind("Cit_Visible") %>'
and this lets the default status of checkbox to be unchecked, so how can I solve this?
You can assign value to text property of checkbox if you want your check box selected at the time of data binding.
<asp:CheckBox ID="chl" runat="Server" Checked="true" Text="<%# Bind('Cit_Visible') %>" />
on code behind you can access text value to save it to in DB
CheckBox MyCheckbox = new CheckBox();
MyCheckbox = (CheckBox)DetailsView1.FindControl("chl");
Response.Write(MyCheckbox.Checked);
When using a DetailsView data control and you have checkbox values you may be starting with an asp:CheckBoxField which handles all the display modes for you. If you want to keep the checkbox binding but also set the default to checked perhaps for an insert you can do the following.
Convert the field to a TemplateField which can be done through the design view of visual studio or manually by replacing this type of block..
<asp:CheckBoxField DataField="Information" HeaderText="Information" SortExpression="Information" />
with a block of code like this
<asp:TemplateField HeaderText="Information" SortExpression="Information">
<EditItemTemplate>
<asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' />
</EditItemTemplate>
<InsertItemTemplate>
<asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' />
</InsertItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
Then to set the checkbox default value to be checked you can do this in the code-behind
Protected Sub dvInformation_PreRender(sender As Object, e As EventArgs) Handles dvInformation.PreRender
If CType(sender, DetailsView).CurrentMode = DetailsViewMode.Insert Then
Dim chk As Object = CType(sender, DetailsView).FindControl("chkInformation")
If chk IsNot Nothing AndAlso chk.GetType Is GetType(CheckBox) Then
CType(chk, CheckBox).Checked = True
End If
End If
End Sub
C# (Converted from VB
protected void dvInformation_PreRender(object sender, EventArgs e)
{
if (((DetailsView)sender).CurrentMode == DetailsViewMode.Insert) {
object chk = ((DetailsView)sender).FindControl("chkInformation");
if (chk != null && object.ReferenceEquals(chk.GetType(), typeof(CheckBox))) {
((CheckBox)chk).Checked = true;
}
}
}
This is obviously best when the supporting database value is a non-null bit field
Use TemplateField:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk1" runat="server" OnInit="chk1_Init" Checked='<%# Bind("Cit_Visible") %>' />
</ItemTemplate>
</asp:TemplateField>
Set the checkbox default value in the Init method:
protected void chk1_Init(object sender, EventArgs e)
{
((CheckBox)sender).Checked = true;
}

asp.net VB gridview checkbox always show false on serverside code behind

I am trying to implement a gridview with checkbox column on asp.net (VB). when the user checks checkbox and click delete button, it should access database and delete all checked item.
I have already tried numerous googled solution and never worked for me. here is short scenario
on my aspx page:
1)search by id text box, when user enter ID and click search button, the below table is displayed
<asp:GridView ID="MyGridView" runat="server">
<Columns>
<asp:TemplateField headertext="Name">
<ItemTemplate>
<asp:Label id="namelbl"
text='<%# Eval("name")%>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete Now?">
<ItemTemplate>
<asp:CheckBox Enabled="true" ID="chkStatus" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
after data is displayed, user checks the desired checkbox and click delete button, then the code behind is run
Protected Sub DelSelected(ByVal sender As Object, ByVal e As System.EventArgs)
Dim idList as ArrayList = new ArrayList()
For Each row As GridViewRow In MyGridView.Rows
Dim selectcb As CheckBox = CType(row.FindControl("chkStatus"), CheckBox)
If (selectcb.Checked) Then
'put into delete list
Trouble starts here, selectcb checkbox is always false
How could that happen, any idea would be appreciated
Thanks
you must bind your data only when no IsPostback in order to persist your checkbox selected, and no reset
If(! IsPostBack)
{
Bind();
}

Use data in repeater when Checkbox is check in ASP.net

I have a repeater for showing my data . this repeater showing 2 field that one of feild is checkBox Control and other is a lable.
NOW , how can I understand text of lable when the checkBox is Checked?
I want to see text of lable in evry row that the CheckBoxes is checksd.
how do I do?
I use LINQtoSQL for get and set data from database
On postback, you need to loop through every row of your repeater, and grab out the checkbox control. Then you can access it's .Checked and .Text properties. If it's .Checked, then add it to a list or array. I can elaborate if needed..
Page...
<asp:CheckBox ID="chkBoxID" runat="server" OnCommand="doSomething_Checked" CommandArgument="<%# Some Binding Information%>"
CommandName="NameForArgument">
</asp:CheckBox>
Code Behind...
protected void doSomething_Checked(object sender, CommandEventArgs e) {
CheckBox ctrl = (CheckBox)sender;
RepeaterItem rpItem = ctrl.NamingContainer as RepeaterItem;
if (rpItem != null) {
CheckBox chkBox = (LinkButton)rpItem.FindControl("chkBoxID");
chkBox.DoSomethingHere...
}
}
<asp:Repeater ID="rptX" runat="server">
<ItemTemplate>
<asp:Label ID="lblX" runat="server" Visible='<%# Eval("IsChecked") %>' />
<asp:CheckBox ID="chkX" runat="server" Checked='<%# Eval("IsChecked") %>' />
</ItemTemplate>
</asp:Repeater>
And code behind when you assign your data
rptX.DataSource = SomeIEnumerableFromLinq; // which has a bool field called IsChecked
rptX.DataBind();

Categories

Resources