I have a radgrid with a radcombobox in each row. I want to get the row's ID after the combo box has been chosen (someone selecting a value in the drop down). I'm using the onitemcreated property of the radgrid to get my method called in code behind. However, I'm not able to read the value of the ID that belongs to the row in which the chosen combo box belongs to. Can anyone provide any suggestions. I have attempted all of Telerik's samples but I'm not getting good results.
As you see in my code below I have a radbutton in the gridtemplatecolumn and this works as expected. When I'm in debug I get   for the value to intID which is not a result I would expect after I select a value from the combo box.
Here is all of my code:
HTML markup:
<telerik:RadGrid ID="rdg1"
runat="server"
ItemStyle-Wrap="false"
TabIndex="1000"
GridLines="Horizontal"
BorderColor="#738BA4"
BorderWidth="1px"
OnNeedDataSource="ds1"
OnItemDataBound="oidb1"
AutoGenerateColumns="False"
OnItemCommand = "oicommand1"
EnableLinqExpressions="true"
OnItemCreated="oicreated1">
<MasterTableView DataKeyNames="ID"
HorizontalAlign="Center"
HeaderStyle-BorderWidth="0"
ItemStyle-BorderWidth="2"
ItemStyle-BorderColor="#738BA4"
FooterStyle-BorderWidth="0"
BorderWidth="0">
<CommandItemSettings ExportToPdfText="Export to Pdf" />
<RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
</RowIndicatorColumn>
<ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
</ExpandCollapseColumn>
<Columns>
<telerik:GridBoundColumn DataField="ID"
ItemStyle-Font-Size="8"
UniqueName="ID"
Visible="false">
<HeaderStyle Wrap="False" />
<ItemStyle Font-Size="8pt" Wrap="False" />
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn ItemStyle-Font-Size="8" HeaderText="Level" UniqueName="Level">
<ItemTemplate>
<telerik:RadComboBox ID="rdcb1" runat="server" AutoPostBack="true"></telerik:RadComboBox>
</ItemTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle Font-Size="8pt" Wrap="False" />
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn ItemStyle-Font-Size="8"
DataField="Name"
UniqueName="Name"
Visible="true"
HeaderText="Name">
<HeaderStyle Wrap="False" />
<ItemStyle Font-Size="8pt" Wrap="true" />
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:ImageButton ID="imgbtn" runat="server" ImageUrl="/Images/Delete-Small.PNG" />
</ItemTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle Wrap="False" />
</telerik:GridTemplateColumn>
</Columns>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column">
</EditColumn>
</EditFormSettings>
<ItemStyle BorderColor="#738BA4" BorderWidth="2px" />
<AlternatingItemStyle />
<HeaderStyle BorderWidth="0px" />
<FooterStyle BorderWidth="0px" />
</MasterTableView>
<ItemStyle Wrap="False" />
<FilterMenu EnableImageSprites="False">
</FilterMenu>
<HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default">
</HeaderContextMenu>
</telerik:RadGrid>
</asp:Panel>
Code behind:
protected void ds1(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e) {
var Role = (from r in db.Role
select new { r.ID, r.Name });
rdg1.DataSource = Role;
Level = Role.Count();
_dataTableLevel.Clear();
_dataTableLevel.Columns.Add("Level");
for (int i = 1; i <= Level; i++) {
DataRow drLevel = _dataTableLevel.NewRow();
drLevel["Level"] = i;
_dataTableLevel.Rows.Add(drOrderLevel);
}
protected void oidb1(object sender, GridItemEventArgs e) {
if (e.Item is GridDataItem) {
GridDataItem Item1 = (GridDataItem)e.Item;
(Item1.FindControl("rdcb1") as RadComboBox).DataValueField = "Level";
(Item1.FindControl("rdcb1") as RadComboBox).DataTextField = "Level";
(Item1.FindControl("rdcb1") as RadComboBox).DataSource = _dataTableLevel.DefaultView;
(Item1.FindControl("rdcb1") as RadComboBox).DataBind();
}
}
protected void oicommand1(object sender, GridCommandEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem Item2 = (GridDataItem)e.Item;
TableCell ID = Item2["ID"] as TableCell;
int intID = Convert.ToInt32(ID.Text);
var deleteRole = (from r in db.Role
where r.ID == intID).First();
db.Role.DeleteObject(deleteRole);
db.SaveChanges();
rdg1.Rebind();
}
}
protected void oicreated1(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem Item3 = (GridDataItem)e.Item;
TableCell ID = Item3["ID"] as TableCell;
string ID = ID.Text;
}
}
The guys at Telerik provided the solution below. The solution by Telerik works.
Thanks.
Thank you for contacting us.
If you want go get the row's ID when you change the selected index of particular combobox, my suggestion is to subscribe on the service-side OnSelectedIndexChanged event and use the following implementation of the event handling function:
protected void OnSelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
var combobox = sender as RadComboBox;
GridDataItem dataItem = combobox.Parent.Parent as GridDataItem;
var text = dataItem["ID"].Text;
}
I hope this would help you out.
Kind regards,
Dimitar Terziev
the Telerik team
your solution works but there is another approach with DataKeyName of RadGrid, if somebody does not ID in columns
protected void RadComboBox1_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
var combobox = sender as RadComboBox;
GridDataItem dataItem = combobox.Parent.Parent as GridDataItem;
string id = dataItem.OwnerTableView.DataKeyValues[dataItem.ItemIndex]["Id"].ToString();
}
Related
I have the following in my .aspx file. When the user clicks on Edit, I like it to show a form where they can Update or Cancel. Currently when I click on Edit, it does nothing. Note that am handling the datasource from the code behind. As such, I do not have a DataSource within the .aspx file for the RadGrid:
Here is my code:
<telerik:RadGrid ID="rdClosedLoop" runat="server" GridLines="None" OnDeleteCommand="DeleteClosedLoop"
Skin="Metro" ActiveItemStyle-HorizontalAlign="Center" AutoGenerateEditColumn="true" >
<MasterTableView EditMode="EditForms" AutoGenerateColumns="False" DataKeyNames="ID" >
<RowIndicatorColumn>
<HeaderStyle Width="20px" />
</RowIndicatorColumn>
<ExpandCollapseColumn>
<HeaderStyle Width="20px" />
</ExpandCollapseColumn>
<Columns>
<telerik:GridBoundColumn DataField="ID" HeaderText="ID" SortExpression="ID" EditFormColumnIndex="0"
UniqueName="ID" HeaderStyle-HorizontalAlign="Center">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="ActiveInhibitor" HeaderText="ActiveInhibitor" SortExpression="ActiveInhibitor" EditFormColumnIndex="0"
UniqueName="ActiveInhibitor" HeaderStyle-HorizontalAlign="Center">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Conductivity" HeaderText="Conductivity" SortExpression="Conductivity" EditFormColumnIndex="0"
UniqueName="Conductivity" HeaderStyle-HorizontalAlign="Center">
</telerik:GridBoundColumn>
<telerik:GridButtonColumn CommandName="Delete" Text="Delete" UniqueName="DeleteColumn">
</telerik:GridButtonColumn>
</Columns>
<EditFormSettings ColumnNumber="1" CaptionFormatString="Edit for ID {0}"
CaptionDataField="ID">
<FormTableItemStyle Wrap="False"></FormTableItemStyle>
<FormCaptionStyle CssClass="EditFormHeader"></FormCaptionStyle>
<FormMainTableStyle GridLines="None" CellSpacing="0" CellPadding="3" Width="100%">
</FormMainTableStyle>
<FormTableStyle GridLines="Horizontal" CellSpacing="0" CellPadding="2" CssClass="module"
Height="110px" Width="100%"></FormTableStyle>
<FormTableAlternatingItemStyle Wrap="False"></FormTableAlternatingItemStyle>
<FormStyle Width="100%" BackColor="#eef2ea"></FormStyle>
<EditColumn UpdateText="Update record" UniqueName="EditCommandColumn1" CancelText="Cancel edit">
</EditColumn>
<FormTableButtonRowStyle HorizontalAlign="Left" CssClass="EditFormButtonRow"></FormTableButtonRowStyle>
</EditFormSettings>
</MasterTableView>
<HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default" EnableImageSprites="True">
</HeaderContextMenu>
</telerik:RadGrid>
Code behind:
protected void btnClosedLoop_Click(object sender, EventArgs e)
{
// Note - verId is based on some conditions
var resultCLList = (from ms in db.ver_ClosedLoop
where ms.VerificationId == verId
select ms).ToList();
rdClosedLoop.DataSource = resultCLList;
rdClosedLoop.DataBind();
}
Please try with the below code snippet.
ASPX
<telerik:RadGrid ID="rdClosedLoop" runat="server" GridLines="None"
Skin="Metro" ActiveItemStyle-HorizontalAlign="Center" AutoGenerateEditColumn="true"
OnItemCommand="rdClosedLoop_ItemCommand">
<MasterTableView EditMode="EditForms" AutoGenerateColumns="False" DataKeyNames="ID">
<RowIndicatorColumn>
<HeaderStyle Width="20px" />
</RowIndicatorColumn>
<ExpandCollapseColumn>
<HeaderStyle Width="20px" />
</ExpandCollapseColumn>
<Columns>
<telerik:GridBoundColumn DataField="ID" HeaderText="ID" SortExpression="ID" EditFormColumnIndex="0"
UniqueName="ID" HeaderStyle-HorizontalAlign="Center">
</telerik:GridBoundColumn>
<telerik:GridButtonColumn CommandName="Delete" Text="Delete" UniqueName="DeleteColumn">
</telerik:GridButtonColumn>
</Columns>
<EditFormSettings ColumnNumber="1" CaptionFormatString="Edit for ID {0}" CaptionDataField="ID">
<FormTableItemStyle Wrap="False"></FormTableItemStyle>
<FormCaptionStyle CssClass="EditFormHeader"></FormCaptionStyle>
<FormMainTableStyle GridLines="None" CellSpacing="0" CellPadding="3" Width="100%">
</FormMainTableStyle>
<FormTableStyle GridLines="Horizontal" CellSpacing="0" CellPadding="2" CssClass="module"
Height="110px" Width="100%"></FormTableStyle>
<FormTableAlternatingItemStyle Wrap="False"></FormTableAlternatingItemStyle>
<FormStyle Width="100%" BackColor="#eef2ea"></FormStyle>
<EditColumn UpdateText="Update record" UniqueName="EditCommandColumn1" CancelText="Cancel edit">
</EditColumn>
<FormTableButtonRowStyle HorizontalAlign="Left" CssClass="EditFormButtonRow"></FormTableButtonRowStyle>
</EditFormSettings>
</MasterTableView>
<HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default" EnableImageSprites="True">
</HeaderContextMenu>
</telerik:RadGrid>
ASPX.CS
protected void Button1_Click(object sender, EventArgs e)
{
rdClosedLoop.DataSource = getDummyData(0);
rdClosedLoop.DataBind();
}
protected DataTable getDummyData(int verId)
{
// Note - verId is based on some conditions
DataTable dt = new DataTable();
dt.Columns.Add("ID",typeof(int));
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);
return dt;
}
protected void rdClosedLoop_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.EditCommandName)
{
rdClosedLoop.DataSource = getDummyData(0);
rdClosedLoop.DataBind();
}
}
Let me know if any concern.
I try using Rad Grid with web Api as data source
<telerik:RadGrid runat="server" ID="grdUsers" AllowPaging="true" AllowSorting="true"
AllowFilteringByColumn="true" PageSize="5">
<MasterTableView AutoGenerateColumns="False" DataKeyNames="Id" ClientDataKeyNames="Id,PasswordHash">
<PagerStyle Mode="NumericPages" AlwaysVisible="true" />
<Columns>
<telerik:GridImageColumn DataType="System.String" DataImageUrlFields="Image" AlternateText="User image"
UniqueName="Image"
ImageAlign="Middle" ImageHeight="50px" ImageWidth="50px" AllowFiltering="false" HeaderText="">
</telerik:GridImageColumn>
<telerik:GridBoundColumn DataField="UserName" HeaderText="User Name" UniqueName="UserName"
DataType="System.String">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="FullName" HeaderText="Name" UniqueName="FullName"
DataType="System.String">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Email" HeaderText="Email" UniqueName="Email"
DataType="System.String">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="RegistrationDate" HeaderText="Registration Date" UniqueName="RegistrationDate"
DataFormatString="{0:dd/MM/yyyy}">
</telerik:GridBoundColumn>
<telerik:GridButtonColumn UniqueName="btnEdit" ButtonType="PushButton" Text="Edit" CommandName="Edit"></telerik:GridButtonColumn>
<telerik:GridButtonColumn UniqueName="btnDelete" ButtonCssClass="del" ButtonType="PushButton" Text="Delete" CommandName="Delete"></telerik:GridButtonColumn>
</Columns>
</MasterTableView>
<ClientSettings>
<Selecting AllowRowSelect="True" />
<ClientEvents OnCommand="RadGridCommand" />
<DataBinding Location="/SecuHostapi/Security/User/GetAll" ResponseType="JSON">
<DataService TableName="SecuHostUser" Type="OData" />
</DataBinding>
</ClientSettings>
</telerik:RadGrid>
Wep Api code
[HttpGet]
public List<SecuHostUser> GetAll(ODataQueryOptions<SecuHostUser> options)
{
UsersRep userRep = new UsersRep();
return userRep.GetAll();
}
although, I have put PageSize="5", the final result show all the data from the data base
This problem can be solved by returning a PageResult instead of a list.
[HttpGet]
public PageResult GetAll(ODataQueryOptions<SecuHostUser> options)
{
UsersRep userRep = new UsersRep();
//return userRep.GetAll();
var users = userRep.GetAll().AsQueryable();
var results = options.ApplyTo(users);
return new PageResult<SecuHostUser>(results as IEnumerable<SecuHostUser>,
Request.GetNextPageLink(), Request.GetInlineCount());
}
I'm trying to get RadGrid to conditionally hide or disable a field when it is in edit mode based on the value of another field.
I have been able to get this to work when the grid displays the list of items, but once the grid enters edit mode, the columns display ...
I am using OnItemDataBound to successfully conditionally display during the initial load, but setting the items when the user clicks a row to get it into batch mode is not working.
Note: PValue and CValue and in GridTemplateColumns, as is CardStatus.
public void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
foreach (GridDataItem item in RadGrid1.Items)
{
string BoundColumnValue = item["CardStatus"].Text; // accessing GridBoundColumn value using ColumnUniqueName
string BoundColumnValue2 = item["CValue"].Text;
TextBox txtbx = (TextBox)item.FindControl("CardStatus");
Label numlb = (Label)item.FindControl("CardValue");
if (txtbx.Text.Equals("True"))
{
txtbx.ForeColor = Color.Red;
numlb.Enabled = false;
numlb.BackColor = Color.Yellow;
numlb.ForeColor = Color.Red;
//Just testing to see if it would evaluate
}
else
{
txtbx.ForeColor = Color.Beige;
}
//string TemplateColumnValue = lb.Text;// accessing Label Text.
}
foreach (GridEditableItem item in RadGrid1.EditItems)
{
string BoundColumnValue = item["CardStatus"].Text; // accessing GridBoundColumn value using ColumnUniqueName
string BoundColumnValue2 = item["CValue"].Text;
TextBox txtbx = (TextBox)item.FindControl("CardStatus");
if (txtbx.Text.Equals("True"))
{
txtbx.ForeColor = Color.Red;
//numTxt.BackColor = Color.Yellow;
//numTxt.ForeColor = Color.Red;
}
else
{
txtbx.ForeColor = Color.Beige;
}
}
}
I just need to be able to selectively prevent data entry in a column
The ASPX source is below:
<telerik:RadGrid ID="RadGrid1" runat="server" AllowAutomaticUpdates="true" Height="930px" DataSourceID="SqlDataSource4" CellSpacing="0" GridLines="None" Width="640px" OnItemDataBound="RadGrid1_ItemDataBound" OnItemCreated="RadGrid1_ItemCreated" OnBatchEditCommand="RadGrid1_BatchEditCommand1" Skin="WebBlue">
<ClientSettings>
<Scrolling AllowScroll="True" UseStaticHeaders="True" />
</ClientSettings>
<MasterTableView AutoGenerateColumns="False" EditMode="Batch" Width="620px" CommandItemDisplay="TopAndBottom" DataSourceID="SqlDataSource4" DataKeyNames="CountKey">
<CommandItemSettings ExportToPdfText="Export to PDF" ShowSaveChangesButton="true" ShowRefreshButton="false" ShowAddNewRecordButton="false"></CommandItemSettings>
<BatchEditingSettings OpenEditingEvent="Click" EditType="Row" />
<RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column">
<HeaderStyle Width="20px"></HeaderStyle>
</RowIndicatorColumn>
<ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
<HeaderStyle Width="20px"></HeaderStyle>
</ExpandCollapseColumn>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
</EditFormSettings>
<PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
<Columns>
<telerik:GridBoundColumn DataField="Pcolumn" ItemStyle-Width="75px" ReadOnly="true" Visible="false" DataType="System.Int32" FilterControlAltText="Filter Pcolumn column" HeaderText="Pcolumn" SortExpression="Pcolumn" UniqueName="Pcolumn">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Row" ReadOnly="true" Visible="false" DataType="System.Int32" FilterControlAltText="Filter Row column" HeaderText="Row" SortExpression="Row" UniqueName="Row">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn ColumnEditorID="PValue" HeaderText="Pattern" DataField="PValue" UniqueName="PValue" ItemStyle-Width="75px" HeaderStyle-Width="75px">
<EditItemTemplate>
<telerik:RadNumericTextBox ID="PValue" Width="50px" runat="server" MaxLength="1" MaxValue="9" NumberFormat-DecimalDigits="0" Text='<%# Bind("PValue") %>'></telerik:RadNumericTextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="PValue" ErrorMessage="<br/>Required (0-9) Only)!" SetFocusOnError="true"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="PValue" Width="50px" runat="server" Text='<%# Bind("PValue") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn ColumnEditorID="CValue" DataField="CValue" HeaderText="Card" UniqueName="CValue" ItemStyle-Width="75px" HeaderStyle-Width="75px">
<EditItemTemplate>
<telerik:RadNumericTextBox ID="CValue" Width="50px" AllowOutOfRangeAutoCorrect="false" runat="server" MaxLength="1" MaxValue="1" NumberFormat-DecimalDigits="0" Text='<%# Bind("CValue") %>'></telerik:RadNumericTextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="CValue" ErrorMessage="<br />Required (0-1 Only)!" SetFocusOnError="true"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CValue" Width="50px" runat="server" Text='<%# Bind("CValue") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="DateEdited" ReadOnly="true" Visible="false" DataType="System.DateTime" FilterControlAltText="Filter DateEdited column" HeaderText="DateEdited" SortExpression="DateEdited" UniqueName="DateEdited">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="CardStatus" DataField="CardStatus" ItemStyle-Width="50px" HeaderStyle-Width="50px">
<ItemTemplate>
<asp:TextBox ID="CardStatus" Width="10px" runat="server" Text='<%# Bind("CardStatus") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="CardStatus" Width="10px" runat="server" Text='<%# Bind("CardStatus") %>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
<PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
<FilterMenu EnableImageSprites="False"></FilterMenu>
</telerik:RadGrid>
Any help / workarounds would be appreciated ... again, "just" need to prevent editing in the CValue column when the CardStatus value is true (bit field) ... using batch mode (using another solution isn't an option now).
Thanks
Larry
Well, this doesn't answer the Telerik question, but ended up doing this with the MS GridView, using the tutorial here: http://msdn.microsoft.com/en-us/library/aa992036(v=vs.90).aspx.
Also was able to customize, and detect hidden grid fields, and hide cells (and disable validators) based on the hidden field's condition.
Added the following code in the RowDataBound event of the gridview:
DataRowView drv = (DataRowView)e.Row.DataItem;
if (drv["Status"].Equals(true))
{
// Find the order of the cell
e.Row.Cells[5].CssClass = "hiddencol"; // using the display: none style
// Find the Validator control in the template column
RequiredFieldValidator reqF = (RequiredFieldValidator)e.Row.Cells[5].FindControl("RequiredFieldValidator1");
reqF.Enabled = false;
}
else
{
}
I am using UpdatePanel and Ajax Tabcontainer. I have one item template column which has both checkbox and radiobutton. Either one of them is visible at a time based on one bit kind of field.
<asp:GridView ID="gvAutoMatchFund" runat="server" AutoGenerateColumns="False" ClientIDMode="Static"
AllowPaging="True" PageSize="50" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None"
OnRowDataBound="gvAutoMatchFund_RowDataBound" BorderWidth="1px" CellPadding="3"
onpageindexchanging="gvAutoMatchFund_PageIndexChanging"
Width="100%">
<Columns>
<asp:BoundField DataField="DYNAMO_FUNDNAME" HeaderText="Dynamo Fund Name" ItemStyle-Width="25%" />
<asp:BoundField DataField="DYNAMO_FUNDID" HeaderText="Dynamo Fund ID" ItemStyle-Width="25%" />
<asp:BoundField DataField="INVESTRAN_FUNDNAME" HeaderText="Investran Fund Name" ItemStyle-Width="25%" />
<asp:BoundField DataField="INVESTRAN_SYSTEMFUNDID" HeaderText="Inv. Sys. Fund ID" />
<asp:TemplateField ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center">
<HeaderTemplate>
<asp:CheckBox ID="chkSelAll" Text="Select" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" Visible='<%#(!(bool)Eval("ISMULTIPLE"))%>' />
<asp:RadioButton ID="rdoSel" runat="server" Visible='<%#((bool)Eval("ISMULTIPLE"))%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#C6E5F5" Font-Bold="True" ForeColor="#4695BD" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
<EmptyDataRowStyle ForeColor="Maroon" />
</asp:GridView>
I am populating it after checking postback
if (!Page.IsPostBack)
{
...
PopulateMyGV();
}
When a button is clicked I am trying to loop thru each item in this gridview and using FindControl method to find checkbox and radiobutton. Upto this point is works however radiobutton checked is always false even if it is selected. However checkbox works fine(gives correct value for checked property) if selected or not. See code below
In button click
foreach (GridViewRow gvr in gvAutoMatchFund.Rows)
{
CheckBox chkSel = (CheckBox)gvr.FindControl("chkSel");
RadioButton rdoSel = (RadioButton)gvr.FindControl("rdoSel");
if (chkSel != null)
{
if (chkSel.Checked)
{
...
}
}
if (rdoSel != null)
{
if (rdoSel.Checked)
{
...
}
}
}
What am I missing?
After spending lot of hours, finally we found that this strange behavior occurs because we were changing the ID of radio button programmatically in RowDataBound event. See the code below.
protected void gvAutoMatchFund_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
USP_MDM_SUGGESTED_AUTOMATCH_FUNDResult objUSP_MDM_SUGGESTED_AUTOMATCH_FUNDResult = (USP_MDM_SUGGESTED_AUTOMATCH_FUNDResult)e.Row.DataItem;
RadioButton rdoSel = (RadioButton)e.Row.FindControl("rdoSel");
rdoSel.ID = "rdoSel_" + objUSP_MDM_SUGGESTED_AUTOMATCH_FUNDResult.DYNAMO_FUNDID
+ "_" + objUSP_MDM_SUGGESTED_AUTOMATCH_FUNDResult.INVESTRAN_SYSTEMFUNDID
+ "_" + objUSP_MDM_SUGGESTED_AUTOMATCH_FUNDResult.INVESTRAN_FUNDID;
}
}
So I removed above logic and used following logic instead to pass various parameters along with radiobutton
protected void gvAutoMatchFund_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
USP_MDM_SUGGESTED_AUTOMATCH_FUNDResult objUSP_MDM_SUGGESTED_AUTOMATCH_FUNDResult = (USP_MDM_SUGGESTED_AUTOMATCH_FUNDResult)e.Row.DataItem;
RadioButton rdoSel = (RadioButton)e.Row.FindControl("rdoSel");
string sValue = "rdoSel_" + objUSP_MDM_SUGGESTED_AUTOMATCH_FUNDResult.DYNAMO_FUNDID
+ "_" + objUSP_MDM_SUGGESTED_AUTOMATCH_FUNDResult.INVESTRAN_SYSTEMFUNDID
+ "_" + objUSP_MDM_SUGGESTED_AUTOMATCH_FUNDResult.INVESTRAN_FUNDID;
rdoSel.Attributes.Add("value", sValue);
}
}
That solved the both issues I described above.
Hi all I am using RadGrid in my application, as I want my RadGrid not to refresh I had my RadGrid in an Update Panel as follows
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RadGrid1" EventName="ItemCommand" />
<%--<asp:PostBackTrigger ControlID="RadGrid1" />--%>
</Triggers>
<ContentTemplate>
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnItemCommand="RadGrid1_ItemCommand"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView Width="950" AutoGenerateColumns="false" DataKeyNames="EmpID" GridLines="None"
TableLayout="Auto">
<Columns>
<telerik:GridBoundColumn DataField="EmpID" HeaderText="Emp ID" ReadOnly="true" HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left" UniqueName="EmpID" FilterControlWidth="30px"
AutoPostBackOnFilter="true" CurrentFilterFunction="Contains" />
<telerik:GridButtonColumn DataTextField="ButtonName" ItemStyle-ForeColor="Blue" CommandName="Generate"
ConfirmTextFields="ButtonName" ConfirmTextFormatString="Would you like to {0} ACH file ?"
ConfirmDialogType="RadWindow" Reorderable="false" UniqueName="ButtonName" ConfirmTitle="ACH File">
</telerik:GridButtonColumn>
<telerik:GridBoundColumn DataField="EmployeeName" HeaderText="Employee Name" ReadOnly="true"
HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" UniqueName="EmployeeName"
FilterControlWidth="60px" AutoPostBackOnFilter="true" CurrentFilterFunction="Contains" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
</ContentTemplate>
</asp:UpdatePanel>
When I click on download button I am unable to download the file this is my code in Itemcommand
protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
if (e.CommandName == "Generate")
{
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment;filename= errorLog.txt");
Response.AddHeader("content-length", "0");
Response.Flush();
Response.End();
}
}
Can some one help me how can I work out this using AsyncPostBackTrigger
You cannot call Response with AsyncPostBack. It is Ajax Framework limitation.
Updated 1/28/2013
Since you are using telerik, I prefer using RadAjaxManager. Basically, when Generate button is clicked, it uses regular post back instead of ajax. In my example, sorting still uses ajax.
<telerik:RadGrid ID="RadGrid1" AutoGenerateColumns="false" AllowSorting="True" runat="server"
OnNeedDataSource="RadGrid1_NeedDataSource" OnItemCommand="RadGrid1_ItemCommand">
<MasterTableView DataKeyNames="EmpID">
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Button runat="server" CommandName="Generate" ID="GenerateButton"
Text="Generate" OnClientClick="Generate(this, event); return false;" />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="EmpID" HeaderText="Emp ID" UniqueName="EmpID" SortExpression="EmpID" />
<telerik:GridBoundColumn DataField="EmployeeName" HeaderText="Employee Name" UniqueName="EmployeeName" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
<%-- RadAjaxManager --%>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadGrid1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
<%-- RadAjaxLoadingPanel --%>
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default">
</telerik:RadAjaxLoadingPanel>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function Generate(sender, e) {
$find("<%= RadAjaxManager1.ClientID %>").__doPostBack(sender.name, "");
}
</script>
</telerik:RadCodeBlock>
public class Employee
{
public int EmpID { get; set; }
public string EmployeeName { get; set; }
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = new List<Employee>
{
new Employee {EmpID = 1, EmployeeName = "John"},
new Employee {EmpID = 2, EmployeeName = "Marry"},
new Employee {EmpID = 3, EmployeeName = "Eric"}
};
}
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == "Generate")
{
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment;filename= errorLog.txt");
Response.AddHeader("content-length", "0");
Response.Flush();
Response.End();
}
}