What is the preferred way to bind a radcombobox in a radgrid? - asp.net

I've seen a lot of questions close to this but haven't found my answer. Here's the key points of my example below:
RadGrid has a GridTemplateColumn
GridTemplateColumn has a RadComboBox in it's EditItemTemplate
RadComboBox is bound to an ObjectDataSource and had a RequiredFieldValidator
SelectedValue='<%#Bind("SomeValue")%>' seems to work but causes validation issues
Setting RadComboBox1.SelectedValue in ItemDataBound event seems to be working
Is binding with code in the ItemDataBound the best way to do this? What's interesting is that setting SelectedValue='<%#Bind("SomeValue")%>' on the aspx page has the SelectedValue already set by the time I get the ItemDataBound but for some reason, a RequiredFieldValidator fails in edit mode when doing this unless I set the value AGAIN in ItemDataBound. Below is a stripped down version of my code.
<telerik:RadGrid ID="rgTasks" runat="server" AllowAutomaticInserts="false" AllowAutomaticUpdates="false" AutoGenerateColumns="False">
<MasterTableView DataKeyNames="Id">
<CommandItemSettings ShowRefreshButton="False"></CommandItemSettings>
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn"></telerik:GridEditCommandColumn>
<telerik:GridBoundColumn DataField="Id" ReadOnly="True" UniqueName="Id" DataType="System.Int32" Visible="false"></telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="TaskTypeId" HeaderText="Task" DataField="TaskTypeId" DefaultInsertValue="">
<ItemTemplate>
<%# Eval("TaskType.Name")%>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox ID="rcbTaskTypeId" runat="server" EmptyMessage="Select TaskType..."
DataSourceID="odsTaskTypes" DataValueField="Id" DataTextField="Name" SelectedValue='<%#Bind("TaskTypeId")%>'>
</telerik:RadComboBox>
<asp:RequiredFieldValidator ID="rfvTaskTypeId" runat="server" ControlToValidate="rcbTaskTypeId" ErrorMessage="Task Type is required" Display="Dynamic"></asp:RequiredFieldValidator>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:ObjectDataSource ID="odsTaskTypes" runat="server" SelectMethod="GetTaskTypes" TypeName="CAPAModel.CAPARepo.DataRepo"></asp:ObjectDataSource>
Protected Sub rgTasks_ItemDataBound(sender As Object, e As GridItemEventArgs) Handles rgTasks.ItemDataBound
If ((TypeOf e.Item Is GridEditableItem) AndAlso e.Item.IsInEditMode) Then
If Not String.IsNullOrEmpty(DataBinder.Eval(e.Item.DataItem, "TaskTypeId").ToString) Then
Dim rcbTaskTypeId As RadComboBox = e.Item.FindControl("rcbTaskTypeId")
rcbTaskTypeId.SelectedValue = DataBinder.Eval(e.Item.DataItem, "TaskTypeId")
End If
End If
End Sub
I saw some relevant questions but am looking for an explanation of how I SHOULD be doing this and why. Thanks.

The error occured because you have set two different datafield as DataValueField and SelectedValue. I suppose you want to show another field as selected other than data in DataValueField and DataTextField. Please take a look into the following code snippet.
ASPX:
<telerik:GridTemplateColumn DataField="test" FilterControlAltText="Filter RegistryValue column" HeaderText="test" SortExpression="test" UniqueName="test">
<EditItemTemplate>
<telerik:RadComboBox ID="RadComboBox1" Runat="server" DataSourceID="odsTaskTypes" DataTextField="Name" DataValueField="Id" >
</telerik:RadComboBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="RegistryValueLabel" runat="server" Text='<%# Eval("RegistryValue") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
C#:
protected void gridiew1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem editItem = (GridEditableItem)e.Item;
RadComboBox combo = (RadComboBox)editItem.FindControl("RadComboBox1");
combo.SelectedItem.Text = (string)DataBinder.Eval(e.Item.DataItem, "TaskTypeId").ToString();
}
}

So I've gone back and forth with Telerik support on this and their suggestion was to just do it the way I'm doing it. Considering that I'm binding the control in the code, I can probably get rid of SelectedValue='<%#Bind("TaskTypeId")%>' like so:
<telerik:RadComboBox ID="rcbTaskTypeId" runat="server"
DataSourceID="odsTaskTypes" DataValueField="Id" DataTextField="Name" >
</telerik:RadComboBox>
...and then just keep the code as is:
Protected Sub rgTasks_ItemDataBound(sender As Object, e As GridItemEventArgs) Handles rgTasks.ItemDataBound
If ((TypeOf e.Item Is GridEditableItem) AndAlso e.Item.IsInEditMode) Then
If Not String.IsNullOrEmpty(DataBinder.Eval(e.Item.DataItem, "TaskTypeId").ToString) Then
Dim rcbTaskTypeId As RadComboBox = e.Item.FindControl("rcbTaskTypeId")
rcbTaskTypeId.SelectedValue = DataBinder.Eval(e.Item.DataItem, "TaskTypeId")
End If
End If
End Sub

Related

Get index from selected Checkbox in DataGrid

I am using DataGrid in Asp.net
<asp:DataGrid>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="chkDetail" runat="server" OnCheckedChanged="chkDetail_CheckedChanged" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Name" HeaderStyle-Font-Bold="true" HeaderStyle-HorizontalAlign="Center">
<EditItemTemplate>
<asp:TextBox runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
As you can see, there is a Checkbox inside DataGrid.
Everytime I check in checkbox, I would like to fire 2 events
1. Other checkboxes will be unselected (I can do it with JS - so it's ok)
2. Context will store DataGrid Name field like this
protected void chkDetail_CheckedChanged(object sender, EventArgs e)
{
Context["Name"] = ??;
}
Because DataGrid doesn't have "Rows" like GridView, I have no idea how to get the Name from the same row.
Thanks in advance.
DataGridViewRow dgvrows = TrGrid.SelectedRows;
string c = dgvrows.Cells("Late_Time").value.toString();
OR
DataGridViewRow dgvrow = this.dataGridView1.Rows[index];
DataRowView drvrow = (DataRowView)dgvrow.DataBoundItem;
You can try this code
protected void chkDetail_CheckedChanged(object sender, EventArgs e)
{
Context["Name"] = (((sender as CheckBox).NamingContainer as DataGridItem).FindControl("label_id") as Label).Text;
}
Your sender will be a CheckBox as the event is triggered by it.
Every control will have a property called NamingContainer which gives the nearest server control that inherits INamingContainer interface. In your case it is DataGridItem. And you can use FindControl method to find child control and cast it to appropriate control type to access its properties.

How to fetch the Value of a LinkButton in a GridView Template Field

I Have a LinkButton In a TemplateField In a GridView. The LinkButton is bound to database which shows the time save in database.All I want is to fetch each linkbutton time value and compare it to current time and if linkbutton time is less than current time ,make it disable.
Any pointers will be helpful.
Thanks in advance.
<asp:GridView ID="grdview" AutoGenerateColumns="false" runat="server" OnRowCommand="grdview_RowCommand">
<Columns>
<asp:BoundField DataField="AudiName" DataFormatString="Audi {0}" HeaderText="Audi Name" />
<asp:TemplateField HeaderText="StartTime">
<ItemTemplate>
<asp:LinkButton ID="lnkmovietime" runat="server"
Text='<%# Eval("StartTime") %>'
CommandName="time"
CommandArgument='<%#Eval("AudiID") %>'>
</asp:LinkButton>
<asp:HiddenField runat="server" ID="hf1" Value='<%#Eval("StartTime")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can use the OnRowDataBound event to hook into the data binding and disable the button.
Form
<asp:GridView ID="MyGridView"
OnRowDataBound="MyGridView_RowDataBound"
runat="server">
....
</asp:GridView>
CodeBehind
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find the button
var linkButton = (LinkButton) e.Row.FindControl("MyLinkButton");
// Toggle enabled/disabled based on time
// Using the button text is probably a bad idea, but is used here for demonstration purposes
linkButton.Enabled = (Convert.ToDateTime(linkButton.Text) > DateTime.Now);
}
}
The code above has not been tested, but should give you an idea of how you can approach this.
You can set the Enabled property of LinkButton comparing with the current time:
<asp:LinkButton ID="lnkmovietime" runat="server"
Text='<%# Eval("StartTime") %>'
Enabled = '<%# ((DateTime)Eval("StartTime")< DateTime.Now )? false : true %>'
CommandName="time" CommandArgument='<%#Eval("AudiID") %>'>
</asp:LinkButton>

Asp.net user control item command event not firing

I have a page which has user control in it.
The page data grid bound columns are populated from user control (user control has a data grid whose items are in the form of item templates).
This user control has a column which contains edit save cancel buttons.
The user control also has other columns which are check boxes,drop down lists inside (item templates).
I am using item command event and when Edit link is clicked it should get current row value of a column called "Description" and for testing purpose I am getting this value into a text box called 'Tdval'.
The Tdval textbox is empty and when I check break point it looks like item command event is not all firing( as break point is not hit).
I don't understand why.
The page is not posted back when I click Edit link.
Its just the user control link button. Please help me.
Excuse any mistakes and am new to this. Thanks in advance.
HTML:
<tr>
<asp:datagrid ID="dgDetails"
EnableViewState="true"
runat="server"
onItemCommand="dgDetails_ItemCommand"
allowpaging="false"
allowcustompaging="false"
autogeneratecolumns="false"
allowsorting="true"
backcolor="white"
Width="100%"
horizontalalign="center"
Font-bold="true"
Font-Names="Verdana"
Font-size="7pt"
BorderColor="Silver" >
<columns>
<asp:BoundColumn DataField="ID" Visible="true"></asp:BoundColumn>
<asp:TemplateColumn HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Left"
HeaderText="Description"
HeaderStyle-Width="320px" >
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server">
<%#DataBinder.Eval(Container.DataItem, "Description")%>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left"
HeaderText="Pr."
HeaderStyle-Width="20px" >
<ItemTemplate>
<asp:CheckBox ID="chkPrimary" runat="server" Enableviewstate="true">
</asp:CheckBox>
</ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server"
CommandName="Edit">Edit
</asp:LinkButton>
</columns>
</asp:datagrid>
</tr>
<tr>
<td>
<asp:TextBox ID="Tdval" runat="server"> </asp:TextBox>
</td>
Code Behind:
Public Sub dgDetails_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgDetails.ItemCommand
Select Case e.CommandName
Case "Edit"
Dim intRow As Integer
intRow = e.Item.ItemIndex
Dim dgRow As DataGridItem
dgRow=dgDetails.Items.Item(intRow)
Dim val As String
val=Ctype(dgRow.Cells(0).Text, String) (Description column)
Tdval.Text=val.Text
End Select
End Sub
I thing u can call bindGrid() method after check page.ispostback on page_load like this :
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
return;
}
BindGrid();
}

Binding value to textbox inside of gridview

I have problems with binding a value of a field inside a gridview to a textbox which is inside the gridview as well. I'm intending to do this for editing the table.
I tried to do this with eval and bind, but the textbox won't show the values and I have absolutely no clue why.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="gvBS" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" SkinID="gvWithoutWidth">
<Columns>
<asp:CommandField ShowEditButton="true" EditImageUrl="~/Images/GridView/gv_edit.png" ButtonType="Image"
CancelImageUrl="~/Images/GridView/gv_cancel.png" UpdateImageUrl="~/Images/GridView/gv_update.png"/>
<asp:TemplateField HeaderText="Sollmonat" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="tbSollMonat" runat="server" Text='<%# Eval("SollMonat") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvSollMonat" ValidationGroup="Update" runat="server"
ControlToValidate="tbSollMonat" ErrorMessage="Bitte Sollmonat (dd.mm.yyyy) angeben"
SetFocusOnError="true">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revSollMonat" ValidationGroup="Update" runat="server"
ValidationExpression="^\d+$" ControlToValidate="tbSollMonat">*</asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<%# Eval("SollMonat")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
The thing is that it works fine inside the ItemTemplate, but doesn't inside the EditItemTemplate-element. Really no clue what the problem is.
Code behind:
Sub gvBS_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs) Handles gvBS.RowEditing
gvBS.EditIndex = e.NewEditIndex
End Sub
Sub gvBS_RowCancelingEdit() Handles gvBS.RowCancelingEdit
Me.gvBS.EditIndex = -1
gvBS_DataBind()
End Sub
I assume that the GridView enters never edit-mode since you aren't handling the RowEditing event or you didn't DataBind it after you've set gvBS.EditIndex = e.NewEditIndex;.
<asp:GridView
OnRowEditing="gvBS_RowEditing" OnRowCancelingEdit="gvBS_RowCancelingEdit"
ID="gvBS" runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" SkinID="gvWithoutWidth">
codebehind (BindGrid is the method which databinds your grid):
protected void gvBS_RowEditing(object sender, GridViewEditEventArgs e)
{
gvBS.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void gvBS_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvBS.EditIndex = -1;
BindGrid();
}
You should also remember to databind it only on the first load, not on consecutive postbacks when ViewState is enabled(default). Therefore you can check the page's IsPostBack property:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
Try the Bind instead of Eval in EditItemTemplate like this
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="gvBS" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" SkinID="gvWithoutWidth">
<Columns>
<asp:CommandField ShowEditButton="true" EditImageUrl="~/Images/GridView/gv_edit.png" ButtonType="Image"
CancelImageUrl="~/Images/GridView/gv_cancel.png" UpdateImageUrl="~/Images/GridView/gv_update.png"/>
<asp:TemplateField HeaderText="Sollmonat" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="tbSollMonat" runat="server" Text='<%# Bind("SollMonat") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvSollMonat" ValidationGroup="Update" runat="server"
ControlToValidate="tbSollMonat" ErrorMessage="Bitte Sollmonat (dd.mm.yyyy) angeben"
SetFocusOnError="true">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revSollMonat" ValidationGroup="Update" runat="server"
ValidationExpression="^\d+$" ControlToValidate="tbSollMonat">*</asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<%# Eval("SollMonat")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>

ASP.NET GridView DropDownList Posts Empty Value

I'm having trouble with a DropDownList within a GridView that posts a NULL value when in fact a value is selected from the list when using inline editing.
The problem is that I can't use this method to bind the value to the UpdateCommand in my SqlDataSource:
SelectedValue='<%# Bind("Value") %>'
The reason for this is because the value might not exist in the list so it throws an exception.
Is there a way I can bind the value to the UpdateCommand without using SelectedValue?
Thanks in advanced.
You may use RowDataBound to set SelectedValue;
in .cs file
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridView grid = (GridView)sender;
DropDownList DropDownList1 = (e.Row.FindControl("DropDownList1") as DropDownList);
HiddenField HiddenField1 = (e.Row.FindControl("HiddenField1") as HiddenField);
DropDownList1.SelectedValue = HiddenField1.Value;
}
in .aspx file;
<Columns>
...
<asp:TemplateField HeaderText="Column Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Value") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("Value") %>'></asp:HiddenField>
<asp:DropDownList ID="DropDownList1" runat="server">
...
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>

Resources