DevExpress AspxGridView filter in ObjectDataSource - asp.net

Yet another problem with DevExpress AspxGridView :)
The context:
One Page
In the Page, a custom control
In the custom Control, a AspxDropDown
The AspxDropDown has a DropDownWindowTemplate
In the DropDownItemTemplate, I add a GridView and a paging/sorting/filtering enabled ObjectDataSource
When handling the selecting event of the ObjectDataSource, I should set filter parameters for the datasource. There filter parameters should come from the FilterRow of the AspxGridView (preferably using the AspxGridView.FilterExpression property).
The problem: the AspxGridView.FilterExpression property is not set to the proper values (set by the user).
Did anyone find a good implementation of what I'm trying to do here?
Thanks a bunch.
:)

I've finally managed to get around the problem.
Not a good solution, but, still, a way to work around it.
So.. The "solution" is to databind the grid on every AfterPerformCallback event.
void grid_AfterPerformCallback(object sender, ASPxGridViewAfterPerformCallbackEventArgs e)
{
((DevExpress.Web.ASPxGridView.ASPxGridView)sender).DataBind();
}
As I've said, it's not a good solution.

The answer per DevExpress is that the correct FilterExpression is updated when it is databound.
They allege that in BeforePerformDataSelect, you will see the correct value.
I have 1 grid that is hooked up to a SqlDataSource that is correctly doing this, and another that is not... So you're mileage may vary.
My second grid wasn't obeying this principal, so I integrated the other guy's concept rebinding in AfterPerformCallback(). The trick is to prevent double querying. This code also demonstrates how to hijack devexpress to build your own SQL. Obviously, this is from my working project, so use your imagination on functions that I have that you don't...
Here is the relevant html and code:
<dxwgv:ASPxGridView ID="grid" runat="server"
KeyFieldName="OrderID"
OnAfterPerformCallback="grid_AfterPerformCallback"
OnBeforePerformDataSelect="grid_BeforePerformDataSelect"
AutoGenerateColumns="True"
SettingsDetail-AllowOnlyOneMasterRowExpanded="true"
Settings-ShowFilterRow="true"
Settings-ShowFilterRowMenu="True"
SettingsBehavior-AllowSelectSingleRowOnly="true"
OnDetailRowExpandedChanged="Grid_DetailRowExpandedChanged"
Styles-Cell-Cursor="pointer"
SettingsBehavior-EnableRowHotTrack="true"
CssFilePath="~/App_Themes/Office2010Blue/{0}/styles.css"
CssPostfix="Office2010Blue"
SettingsPager-PageSize="<%# this._GridRowsPerPage %>"
SettingsBehavior-ColumnResizeMode="Control"
SettingsCustomizationWindow-PopupHorizontalAlign="WindowCenter"
SettingsCustomizationWindow-PopupVerticalAlign="WindowCenter"
SettingsCustomizationWindow-Width="300px"
Settings-ShowHorizontalScrollBar="true"
Width="<%# this._GetWidth() %>"
SettingsPager-AlwaysShowPager="true"
SettingsCookies-Enabled="true"
>
<Columns>
<dxwgv:GridViewDataColumn FieldName="PriorityType" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="basePatientID" Caption="PTID" />
<dxwgv:GridViewDataColumn FieldName="FirstName" />
<dxwgv:GridViewDataColumn FieldName="LastName" />
<dxwgv:GridViewDataColumn FieldName="Employer" />
<dxwgv:GridViewDataColumn FieldName="Insurer" />
<dxwgv:GridViewDataColumn FieldName="ClaimJurisdiction" Caption="Jurisdiction" />
<dxwgv:GridViewDataColumn FieldName="DOB" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="DateOfInjury" Caption="DOI" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="PostalCode" Caption="ZipCode" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="FirstCareDate" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="LastCareDate" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="IntakeStatus" />
<dxwgv:GridViewDataColumn FieldName="SchedulingNeeded" />
<dxwgv:GridViewDataColumn FieldName="InitialReferralDate" Caption="Date Assigned" />
<dxwgv:GridViewDataColumn FieldName="Orders_UpdatedOn" Caption="Last Follow-up" />
<dxwgv:GridViewDataColumn FieldName="RequestTypes" Caption="Service" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="FacilityGroups" Caption="Provider" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="ICD9Codes" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="CPTCodes" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="OrderCategory" Caption="Source" />
<dxwgv:GridViewDataColumn FieldName="CaseCoordinator" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="SchedulingTier" Visible="false" Caption="Tier" />
<dxwgv:GridViewDataColumn FieldName="LockRequest_UserName" Visible="true" Caption="InUseBy" />
</Columns>
<Styles CssFilePath="~/App_Themes/Office2010Blue/{0}/styles.css" CssPostfix="Office2010Blue">
<Header ImageSpacing="5px" SortingImageSpacing="5px">
</Header>
<LoadingPanel ImageSpacing="10px">
</LoadingPanel>
</Styles>
<ImagesFilterControl>
<LoadingPanel Url="~/App_Themes/Office2010Blue/Editors/Loading.gif">
</LoadingPanel>
</ImagesFilterControl>
<Images SpriteCssFilePath="~/App_Themes/Office2010Blue/{0}/sprite.css">
<LoadingPanelOnStatusBar Url="~/App_Themes/Office2010Blue/GridView/gvLoadingOnStatusBar.gif">
</LoadingPanelOnStatusBar>
<LoadingPanel Url="~/App_Themes/Office2010Blue/GridView/Loading.gif">
</LoadingPanel>
</Images>
<ClientSideEvents ContextMenu="grid_ShowContextMenu" />
<ClientSideEvents BeginCallback="function(s, e) { OnBeginCallback(s,e); }" />
<ClientSideEvents EndCallback="function(s, e) { OnEndCallback(s,e); }" />
<StylesEditors>
<ProgressBar Height="25px">
</ProgressBar>
</StylesEditors>
</dxwgv:ASPxGridView>
<asp:SqlDataSource ID="GridSource" runat="server"></asp:SqlDataSource>
And here's the event handler for BeforePerformDataSelect:
private bool _DataBindingCompleted = false;
protected void grid_BeforePerformDataSelect(object sender, EventArgs e)
{
if (_DataBindCompleted) Grid_PerformDataSelect(sender, e);
}
protected override void Grid_PerformDataSelect(bool ClearSelection)
{
if (ClearSelection) this.grid.Selection.UnselectAll();
GridSource.ProviderName = System.Configuration.ConfigurationManager.ConnectionStrings["mysql"].ProviderName;
GridSource.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["mysql"].ConnectionString;
SetupSearch();
//if (this.FilterContext.Count > 0 || !string.IsNullOrEmpty(grid.FilterExpression))
//{
string FilterSQL = DevExpressUtils.GetMySQLFilterExpression(grid);
string OrderBySQL = DevExpressUtils.GetSQLOrderByExpression(grid, "OrderID");
//FilterSQL = FilterSQL.Replace("[PatientID]", "vwPatients."+ Patient.PRIMARYKEY);
if (Utils.GetAppSettingBool("MYSQL"))
{
GridSource.SelectCommand = this.MP.CurrentUser.GetEOSHeaderSQL(this.FilterContext, FilterSQL, "");
}
else
{
GridSource.SelectCommand = "";
}
}
protected override void Grid_PerformDataSelect(object sender, EventArgs e)
{
bool IsFromParent = this.ClientID.StartsWith(this.MP.GridCallback);
if (grid.Visible && (!this.Page.IsCallback ||
((this.MP.GridCallback == this.grid.ClientID && (this.MP.GridCallbackCommand != "SHOWDETAILROW" || this.IsDetailGrid))
|| (this.MP.GridCallbackCommand == "SHOWDETAILROW" && IsFromParent)
)
)
)
{
Grid_PerformDataSelect(false);
}
}
protected void grid_AfterPerformCallback(object sender, ASPxGridViewAfterPerformCallbackEventArgs e)
{
_DataBindCompleted = true;
((DevExpress.Web.ASPxGridView.ASPxGridView)sender).DataBind();
}
protected void Page_Init(object sender, EventArgs e)
{
grid.DataSource = GridSource;
}
protected new void Page_Load(object sender, EventArgs e)
{
this.grid.ClientInstanceName = this.grid.ClientID;
if (!this.IsPostBack)
{
_DataBindCompleted = true;
grid.DataBind();
}
}

Related

Unable to get selected item of dx:ASPxListBox on ASPxGridView_Updating event of devexpress control

I have used dx:ASPxGridView where I have one dx:GridViewDataTextColumn with EditItemTemplate which contain dx:ASPxListBox. When I click on update command I am not able to get selected items of dx:ASPxListBox under ASPxGridView_Updating.
<dx:ASPxGridView
ID="ASPxGridView"
runat="server"
AutoGenerateColumns="False"
DataSourceID="TradersDS"
KeyFieldName="TraderId">
<SettingsEditing Mode="PopupEditForm" PopupEditFormWidth="600px" />
<ClientSideEvents RowDblClick="function(s, e)
{
s.StartEditRow(e.visibleIndex);
}"
EndCallback="PrepareGridViewForNewDesing" Init="PrepareGridViewForNewDesing" />
<Columns>
....
<dx:GridViewDataTextColumn FieldName="CounterParty" VisibleIndex="3">
<EditItemTemplate>
<dx:ASPxListBox ID="lstCounterParty" runat="server" SelectionMode="CheckColumn" EnableSelectAll="true"
Width="285"
Height="300"
DataSourceID="CounterPartiesDS"
ValueField="ID"
ValueType="System.String"
TextField="Name">
<%-- <ClientSideEvents SelectedIndexChanged="function(s, e) {lbModels.PerformCallback('1');}" />--%>
</dx:ASPxListBox>
</EditItemTemplate>
</dx:GridViewDataTextColumn>
...
</Columns>
</dx:ASPxGridView>
C# Code..
protected override void ASPxGridView_Updating(object sender, ASPxDataUpdatingEventArgs e)
{
var gridView = sender as ASPxGridView;
GridViewDataColumn list = gridView.Columns["CounterParty"] as GridViewDataColumn;
var counterPartyListBox = (ASPxListBox)gridView.FindEditRowCellTemplateControl(list, "lstCounterParty");
string selectedItemsAsString = string.Empty;
foreach (ListEditItem item in counterPartyListBox.SelectedItems)
selectedItemsAsString += item.Value + ";";
base.ASPxGridView_Updating(sender, e);
}
Here I always get count 0 of SelectedItems. On addition to this My devExpress control version are 9.3.3
What is wrong with this code any help , guidance really appreciated.
Make sure that you set the ASPxListBox.ValueType property to the corresponding .NET type that matches the type of the "ValueField" column.
May be, according to the (ValueField="ID"), the (ASPxListBox.ValueType) should be numeric? (System.Int32, etc.)

pass UNiqueIdentifier to another asp.net page

I have coded this page
I need to pass the uniqueidentifier to another page, i have try these ways :
e.Row.Cells[1].Text = "<a href='Clientes.aspx?UserName='>" + e.Row.Cells[0].Text + "</a>";
and this
Response.Redirect("~/Clientes.aspx?Nome=" + e.Row.Cells[0].Text);
what the best and secure way to pass the GUID to another page ???
Thanks
Alejandro Carnero
In the codebehind of your first page, store the unique identifier in a Session variable, and then redirect to the "Clients" page normally:
Session["myUniqueID"] = e.Row.Cells[0].Text;
Response.Redirect("~/Clientes.aspx");
Then, in the codebehind of "Clientes.aspx", retreive it:
protected void Page_Load(object sender, EventArgs e)
{
string myUniqueID = Session["myUniqueID"].ToString();
}
Note: I use "Page_Load" as an example, you could put this code in whatever method you want.
I have solved this way , source page :
<tr>
<td colspan="3">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="False"
CellPadding="4" ForeColor="#333333" GridLines="None" Width="770px" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:HyperLinkField Text="Mostrar Cadastro" DataNavigateUrlFields="idcliente"
DataNavigateUrlFormatString="~/Clientes.aspx?ID={0}"
/>
<asp:BoundField DataField="idcliente" HeaderText="ID" />
<asp:BoundField DataField="nome" HeaderText="Nome" />
<asp:BoundField DataField="endere" HeaderText="Endereço" />
<asp:BoundField DataField="Tel" HeaderText="Telefone" />
<asp:BoundField DataField="pedido" HeaderText="Pedido" />
Destiny page :
protected void Page_Load(object sender, EventArgs e)
{
LblIDCliente.Text = Request.QueryString["ID"];
}

How can i can change devexpress custom button text?

<bimsa:GridViewBase ID="gridYorum" runat="server" KeyFieldName="Id" ClientInstanceName="gridYorumClient" OnCustomButtonCallback="StatuGuncelleCallBack"
KaynakKodu="0" Width="100%" OnCustomCallback="grid_CustomCallback" >
<ClientSideEvents EndCallback="function(s, e) {
}" />
<Columns>
<bimsa:DataColumn FieldName="Statu" Visible="false" ></bimsa:DataColumn>
<bimsa:DataColumn FieldName="Yorum" Width="430px" Caption="<%$Resources: Controls, Yorum %>" VisibleIndex="1"></bimsa:DataColumn>
<bimsa:DataColumn FieldName="OlusturanKullanici" Width="100px" Caption="<%$Resources: Controls, YorumSahibi %>" VisibleIndex="2" ></bimsa:DataColumn>
<bimsa:DateTimeColumn FieldName="OlusturmaZamani" Width="100px" Caption="<%$Resources: Controls, YorumZamani %>" VisibleIndex="3" ></bimsa:DateTimeColumn >
<bimsa:CommandColumn KaynakKodu="123">
<CustomButtons>
<bimsa:CustomButton ID="statuGuncelle" Text="Okundu Yap / Okunmadı Yap">
</bimsa:CustomButton>
</CustomButtons>
</bimsa:CommandColumn>
</Columns>
I have a custom button which id's is statuGuncelle and when I click it, I want to change text on this button using this event
c#
protected void StatuGuncelleCallBack(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
{
BIMSA.Web.UI.Controls.GridViewBase grd = (BIMSA.Web.UI.Controls.GridViewBase)sender;
var key=grd.GetRowValues(e.VisibleIndex, grd.KeyFieldName);
...................
i have fixed problem to use this code.
gridYorum.CustomButtonInitialize += new ASPxGridViewCustomButtonEventHandler(gridYorum_CustomButtonInitialize);
void gridYorum_CustomButtonInitialize(object sender, ASPxGridViewCustomButtonEventArgs e)
{
String statu = gridYorum.GetRowValues(e.VisibleIndex, "Statu").ToString();
if (statu == "Okundu")
{
e.Text = "Okunmadı yap";
}
}

ext.net.row editing ,how to triger update event fire ( OnBeforeRecordUpdated)

I have a srote like this
<ext:Store ID="strPos" runat="server" AutoSync="false" OnReadData="StoreChange_Event"
OnBeforeRecordUpdated="StorePostGuncelle" OnBeforeRecordInserted="StorePostEkle"
AutomaticResponseValues="false" OnBeforeRecordDeleted="StorePosSil">
I can ınserting values like that way,
grid.store.insert(0, r);
#{strPos}.sync();
grid.store.reload();
but the problem is when updating the value .when clcik the row ,open row editor,then I clcik the update button but no event fire .(I wanna fireOnBeforeRecordUpdaten event ).
I have already tried this ,
<Plugins>
<ext:RowEditing ID="RowEditing1" runat="server" CancelBtnText="İptal" SaveBtnText="Kaydet" ClicksToEdit="1" TriggerEvent="#{strPos}.sync();#{strPos}.reload();" >
</ext:RowEditing>
</Plugins>
and this one
<Plugins>
<ext:RowEditing ID="RowEditing1" runat="server" CancelBtnText="İptal" SaveBtnText="Kaydet" ClicksToEdit="1" SaveHandler="#{strPos}.sync();#{strPos}.reload();" SaveHandler="" >
</ext:RowEditing>
</Plugins>
but change nothing.
thank you
**
it is availbale this.up('gridpanel').store.removeAt(recordIndex); and insert method but where is the update method.
EDITED: complete example ;
<ext:XScript ID="XScript1" runat="server">
<script>
function addPlant(btn) {
// Create a model instance
var grid = #{GridPanel1};
grid.editingPlugin.cancelEdit();
var r = Ext.ModelManager.create({
Adi: 'pos bilgisi',
Id:'0'
} ,'Pos');
grid.store.insert(0, r);
#{strPos}.sync();
grid.store.reload();
// grid.editingPlugin.startEditByPosition({ row: 0, column: 1 });
}
</script>
</ext:XScript>
<ext:GridPanel ID="GridPanel1" Scroll="Vertical" runat="server" Title="Pos tanımlamalrı"
Height="200">
<Store>
<ext:Store ID="strPos" runat="server" AutoSync="false" OnReadData="StoreChange_Event" OnAfterStoreChanged="store_change"
OnBeforeRecordUpdated="StorePostGuncelle" OnBeforeRecordInserted="StorePostEkle"
AutomaticResponseValues="false" OnBeforeRecordDeleted="StorePosSil">
<Model>
<ext:Model ID="Model1" runat="server" Name="Pos">
<Fields>
<ext:ModelField Name="Id" Type="Int" SortDir="ASC" />
<ext:ModelField Name="Adi" Type="String" />
</Fields>
</ext:Model>
</Model>
</ext:Store>
</Store>
<TopBar>
<ext:Toolbar ID="Toolbar1" runat="server">
<Items>
<ext:Button ID="Button1" runat="server" Text="Pos ekle" Handler="addPlant" Icon="Add" />
</Items>
</ext:Toolbar>
</TopBar>
<ColumnModel ID="ColumnModel1" runat="server">
<Columns>
<ext:Column ID="Column7" runat="server" Text="Id" DataIndex="Id" Flex="1">
</ext:Column>
<ext:Column ID="Column8" runat="server" Text="Banka adı" DataIndex="Adi" Flex="1">
<Editor>
<ext:TextField ID="txtAd" runat="server" AllowBlank="false" />
</Editor>
</ext:Column>
<ext:ImageCommandColumn ID="ImageCommandColumn1" runat="server" Width="30" Sortable="false">
<Commands>
<ext:ImageCommand Icon="Decline" ToolTip-Text="Delete Plant" CommandName="delete">
</ext:ImageCommand>
</Commands>
<Listeners>
<Command Handler="this.up('gridpanel').store.removeAt(recordIndex);#{strPos}.sync();" />
</Listeners>
</ext:ImageCommandColumn>
</Columns>
</ColumnModel>
<SelectionModel>
<ext:RowSelectionModel ID="rowSelectionModel1" runat="server">
</ext:RowSelectionModel>
</SelectionModel>
<Plugins>
<ext:RowEditing ID="RowEditing1" runat="server" CancelBtnText="İptal" SaveBtnText="Kaydet" ClicksToEdit="0" SaveHandler="#{strPos}.sync();" >
</ext:RowEditing>
</Plugins>
</ext:GridPanel>
and the code behind is here
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
strPos.DataSource = ps.Getir();
strPos.DataBind();
}
}
protected void StoreChange_Event(object sender, EventArgs e)
{
strPos.DataSource = ps.Getir();
strPos.DataBind();
}
protected void store_change(object sender, AfterStoreChangedEventArgs e)
{
strPos.DataSource = ps.Getir();
strPos.DataBind();
}
public void StorePostEkle(object sender, BeforeRecordInsertedEventArgs e)
{
// string ss = e.Record.ToString();
Pos pss = e.Object<Pos>();
ps.Ekle(pss);
X.Msg.Notify("store", "storea veri eklendi" + e.Record).Show();
// GridPanel1.Reload();
}
protected void StorePosSil(object sender, BeforeRecordDeletedEventArgs e)
{
X.Msg.Notify("store", "storea dan veri, silindi " + e.Record).Show();
Pos pss = e.Object<Pos>();
try
{
ps.Sil(pss.Id);
}
catch (Exception)
{
throw;
}
}
protected void StorePostGuncelle(object sender, BeforeRecordUpdatedEventArgs e)
{
X.Msg.Notify("store", "storea güncellendi " + e.Record).Show();
Pos pss = e.Object<Pos>();
// Pos pss = JSON.Deserialize<Pos>(e.ToString());
ps.Guncelle(pss);

How to find a dynamic control (radio button) inside a placeholder in gridview

I have gridview with 4 columns; in column 1 I added a place holder and other 3 columns are boundfields. In column 1 I'm adding radio buttons dynamically using html code by which I am able to select only one radio button. It's working well, but the problem is I am unable to find the radio button control when a button outside of the gridview is clicked.
Please help, I've been stuck on this problem for 4 days.
Thank you in advance.
I used the following code
.aspx File
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" ForeColor="Black" GridLines="Vertical"
onrowdatabound="GridView1_RowDataBound"
>
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="FIRST NAME" DataField="FNAME"/>
<asp:BoundField HeaderText="LAST NAME" DataField="LNAME"/>
<asp:BoundField HeaderText="EMAIL" DataField="EMAIL"/>
<asp:BoundField HeaderText="AGE" DataField="AGE"/>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
<asp:Button ID="btnSave" Text="Save" runat="server" onclick="btnSave_Click1" />
</form>
Code Behind file
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex != -1 && e.Row.DataItem != null)
{
PlaceHolder holder = (PlaceHolder)e.Row.FindControl("ph");
RadioButton rb = new RadioButton();
rb.ID = "rbSelect";
holder.Controls.Add(rb);
}
}
protected void btnSave_Click1(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
PlaceHolder holder = (PlaceHolder)GridView1.Rows[i].Cells[0].FindControl("ph");
RadioButton rbtn = holder.FindControl("rb") as RadioButton;
if (rbtn.Checked == true)
{
Response.Write("<Script>alert('Radiocheck')</Script>");
}
}
}
It's not clear why you need to create dynamic RadioButtons at all. That makes all just more difficult without a benefit in this case(even if, a nested Repeater or GridView would be easier).
However,
you should not create dynamic controls in RowDataBound since that is triggered only if the GridView was databound. But since by default ViewState is enabled you wouldn't DataBind it on postbacks. Dynamic controls on the other hand must be recreated on every postback.
Therefore create them in RowCreated which is triggered on every postback. But note that you have (of course) no DataItem there since it is null at this stage(even if the grid will be databound).
So you should create cynamic controls in RowCreated but load them from RowDataBound where you can also access them (f.e. via FindControl).
But instead of adding html-control like <input type='radio' you should create and add a RadioButton with an id. Otherwise you won't be able to acess it later, so holder.FindControl("rb") will, be null since it's not a server-control.
Here's the complete modified code:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
PlaceHolder holder = (PlaceHolder)e.Row.FindControl("ph");
var rb = new RadioButton();
rb.ID = "RbSample";
rb.Text = "rb";
holder.Controls.Add(rb);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var row = ((DataRowView)e.Row.DataItem).Row;
var rb = (RadioButton)e.Row.FindControl("RbSample");
rb.Checked = row.Field<bool>("SampleActive");
}
}
protected void btnSave_Click1(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
RadioButton rbtn = (RadioButton)GridView1.Rows[i].FindControl("RbSample");
if (rbtn.Checked)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Radiocheck');", true);
}
}
}
It looks like you are doing FindControl with the "value" of the input, but not with the ASP.NET ID of the control, because it has none. Because it's not an ASP.NET control you cannot find it with FindControl.
I also don't know if you can loop through the Controls property of holder, because it's a plain html control. But you can try it out to put a breakpoint on the FindControl line and explore the Controls property of holder.

Resources