Delete multiple row with radgrid - telerik

I am using Radgrid view with multi select row
I want to delete all selected records using checkbox in RadGrid
Code:
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False"
OnNeedDataSource="RadGrid1_NeedDataSource"
AllowMultiRowSelection="true">
<MasterTableView DataKeyNames="ID">
<Columns>
<telerik:GridClientSelectColumn>
</telerik:GridClientSelectColumn>
<telerik:GridBoundColumn DataField="Name" UniqueName="Name" HeaderText="Name">
</telerik:GridBoundColumn>
<telerik:GridEditCommandColumn>
</telerik:GridEditCommandColumn>
</Columns>
</MasterTableView>
<ClientSettings>
<Selecting AllowRowSelect="true" />
</ClientSettings>
</telerik:RadGrid>
.aspx.vb
Protected Sub Button1_Click(sender As Object, e As EventArgs)
For Each item As GridDataItem In RadGrid1.SelectedItems
If item.Selected Then
'Access data key
Dim strID As String = item.GetDataKeyValue("ID").ToString()
End If
NEXT
End Sub
The problem is when I use this method to get selected rows IDs to delete records, it is retrieving only one record ID and deleting the record for which the ID is retrieved.
Example: I am selecting records 1,2,3,4 and clicking the delete button, it is deleting only the record with ID=4

I don't know vs Basic very well. But I can say that,
you are loose your current ID knowledge in this command
Dim strID As String = item.GetDataKeyValue("ID").ToString()
every iteration in foreach, your strId variable update with new item id.
Maybe you can use concat string methods (maybe
strId += item.id
to save your all selected ids.

Try below code:
protected void Button1_Click(object sender, EventArgs e)
{
string strID = string.Empty;
foreach( GridDataItem grditem in RadGrid.SelectedItems)
{
if (grditem.Selected)
{
strID = strID + "," + grditem.GetDataKeyValue("ID").ToString();
}
}
if (strID != string.Empty)
{
//your delete logic for db
// pass strID it will contain 1,2,3,4
}
}

Related

Issue with oncheckchanged in vb.net

I have a page with many gridviews. They are in 2 columns 5 on the left and 5 on the right. They are exactly the same.
The Gridview for Employment has a template for a checkbox on the far left. When this is checked, it fires the following:
Protected Sub ChckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim row As GridViewRow = TryCast((CType(sender, Control)).Parent.NamingContainer, GridViewRow)
Dim key As String = GridView5.DataKeys(row.RowIndex).Value.ToString()
Dim Incomeadapter As New DataSet1TableAdapters.IncomeTableAdapter
Dim tblincome As New DataSet1.IncomeDataTable
tblincome = Incomeadapter.GetData(key)
GridView6.DataSource = tblincome
GridView6.DataBind()
Exit Sub
I have debugged this, and this code for some reason I don't understand is LOOPING around! Why does it does this? The first time around it gets the correct info, but then it goes back around and ruins the binding of the gridview to the tableadapter because the wrong ID was put into the call to the tableadapter funcion. Is it possible that OncheckChanged event does not work well with the onclick event? I'm using javascript to make sure that only 1 checkbox can be selected on the gridview on the same checkbox :
<div style="overflow-x: scroll; overflow-y: scroll; height: 100px; width: 444px">
<asp:GridView ID="GridView5" runat="server" DataSourceID="SqlDataSource5" AutoGenerateColumns="False" CellPadding="2" HorizontalAlign="Center" OnRowDataBound="Gridview5_rowdatabound" DataKeyNames="EmpID" RowStyle-Wrap="False" HeaderStyle-Wrap="False" ShowHeader="False" ShowFooter="True" FooterStyle-BackColor="Black">
<FooterStyle BackColor="Black"></FooterStyle>
<HeaderStyle Wrap="False"></HeaderStyle>
<RowStyle HorizontalAlign="Center" />
<Columns>
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:CheckBox ID="ChkSelect" runat="server" onclick="CheckOne(this)" AutoPostBack="True" OnCheckedChanged="ChckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<script type="text/javascript">
function CheckOne(obj) {
var grid = obj.parentNode.parentNode.parentNode;
var inputs = grid.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (obj.checked && inputs[i] != obj && inputs[i].checked) {
inputs[i].checked = false;
}
}
}
}
</script>
Rather than doing a postback, with this checkbox with autopostback set to true, is there a way to bind the income gridview which is below the employment gridview without a postback? The income gridview has a separate sql table which has the ID of the employer table as a column. The idea is when you check a checkbox on gridview5 (employment) the income gridview below changes to show the income items which are reflected of the employer. There can be multiple types of income for each employer. Any advice greatly appreciated.
' CausesValidation="False" />
' />
I was able to fix the "looping" issue by rewriting the code as follows:
Dim key As String = ""
For Each row As GridViewRow In GridView5.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim chkrow As CheckBox = TryCast(row.Cells(0).FindControl("ChkSelect"), CheckBox)
If chkrow.Checked Then
key = GridView5.DataKeys(row.RowIndex).Value.ToString()
End If
End If
Next
'Dim row As GridViewRow = TryCast((CType(sender, Control)).Parent.NamingContainer, GridViewRow)
Dim Incomeadapter As New DataSet1TableAdapters.IncomeTableAdapter
Dim tblincome As New DataSet1.IncomeDataTable
tblincome = Incomeadapter.GetData(key)
GridView6.DataSource = tblincome
GridView6.DataBind()
It is working correctly, however on every postback the page goes up to the top and this is just not acceptable, so I would like to try it with Ajax and update panels. I'm reading up on this now.

How can I set textbox to read only using a Telerik Radgrid UserControl

I have a Telerik RadGrid using a User Control for edit an Insert. Configured like this
<MasterTableView AutoGenerateColumns="false" CommandItemDisplay="Top"
DataKeyNames="Form_UsageId" Font-Size="Medium"
NoMasterRecordsText="No Transfer Locker Records Added" InsertItemPageIndexAction="ShowItemOnCurrentPage"
CommandItemSettings-AddNewRecordText="Add New Transfer Locker Entry">
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn"></telerik:GridEditCommandColumn>
<telerik:GridBoundColumn UniqueName="CaseNumber" HeaderText="Case Number" DataField="CaseNumber"></telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="ItemCount" HeaderText="# of Items" DataField="ItemCount"></telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="PersonFor" HeaderText="Person Intended For" DataField="PersonIntendedFor"></telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="PersonAdding" HeaderText="Person Putting In" DataField="PersonAdding"></telerik:GridBoundColumn>
<telerik:GridDateTimeColumn DataField="DateIn" HeaderText="Date Put In"
PickerType="DatePicker" EnableTimeIndependentFiltering="true" DataFormatString="{0:MM/dd/yyyy}">
</telerik:GridDateTimeColumn>
<telerik:GridBoundColumn UniqueName="TotalDays" HeaderText="# Days Open" DataField="TotalDays"></telerik:GridBoundColumn>
</Columns>
<EditFormSettings UserControlName="TransferLockerUserControl.ascx" EditFormType="WebUserControl" PopUpSettings-Modal="false">
<EditColumn UniqueName="EditCommandColumn1"></EditColumn>
</EditFormSettings>
</MasterTableView>
I am using a User Control for editing a record and I need to set some of the text boxes to read only. This is what I have tried
if (e.Item.IsInEditMode && e.Item is GridEditableItem)
{
if (e.Item.ItemIndex == -1)
{
// insert
GridEditableItem item = e.Item as GridEditableItem;
}
else
{
// edit
GridEditableItem item = e.Item as GridEditableItem;
(item["CaseNumber"].Controls[0] as TextBox).ReadOnly = true;
}
}
This fails and generates the error
Can someone help me fix this?
I was able to find the answer to this problem I have posted the working code below.
if (e.Item.IsInEditMode && e.Item is GridEditableItem)
{
if (e.Item.ItemIndex == -1)
{
// insert
GridEditableItem item = e.Item as GridEditableItem;
}
else
{
// edit
GridEditableItem item = e.Item as GridEditableItem;
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
TextBox txt = (TextBox)userControl.FindControl("txtCaseNumber"); //access TextBox here
txt.ReadOnly = true;
}
}

Telerik Grid - Get master ID in details view

I have a master/detail grid where I do inserts on both the master and detail views. When I'm in detail mode, I need to obtain the master ID value but I can't seem to obtain the value.
I first obtain the inserteditem in the InsertCommand:
Dim inserteditem As GridDataInsertItem = DirectCast(e.Item, GridDataInsertItem)
And then I obtain an instance of the parent (master) view:
Dim parenttable As GridTableView = inserteditem.OwnerTableView.ParentItem.OwnerTableView
I just can't seem to get to the master key value, however. Anyone know what I should do?
Please try with the below code snippet.
.ASPX
<MasterTableView CommandItemDisplay="Top" DataKeyNames="ID" Name="parent">
<DetailTables>
<telerik:GridTableView Name="Child" DataKeyNames="Name">
</telerik:GridTableView>
</DetailTables>
<Columns>
........
........
</Columns>
</MasterTableView>
.ASPX.VB
Protected Sub RadGrid1_InsertCommand(sender As Object, e As GridCommandEventArgs)
If e.Item.OwnerTableView.Name = "Child" Then
Dim item As GridDataInsertItem = TryCast(e.Item, GridDataInsertItem)
Dim pitem As GridDataItem = TryCast(item.OwnerTableView.ParentItem, GridDataItem)
' Parent Item DataKey Here
Dim strID As String = pitem.GetDataKeyValue("ID").ToString()
End If
End Sub

Populate ListBox in GridTemplateColumn in InsertItemTemplate

How do I populate a listbox that is located in the InsertItemTemplate? I need to poplulate this after someone clicks the add new record button and I need to do this in the code behind after they click.
There are few ways of doing it. I prefer Template Edit Form. Here is the sample.
<telerik:RadGrid ... OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView DataKeyNames="Id" CommandItemDisplay="Top">
<Columns>
<telerik:GridButtonColumn .../>
</Columns>
<EditFormSettings ColumnNumber="1" EditFormType="Template">
<FormTemplate>
<asp:ListBox .../>
</FormTemplate>
</EditFormSettings>
</MasterTableView>
</telerik:RadGrid>
Updated:
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
{
var item = e.Item as GridEditFormItem;
var listBox1 = item.FindControl("ListBox1") as ListBox;
// Fills listbox with data
listBox1.DataSource = listboxdata;
listBox1.DataBind();
}
}

Conditional Item Templates with RadComboBox

I have a RadComboBox that I am using to display department name and abbreviations. I am using an Item Template with a LinqDataSource to make each item appear as:
DeptAbbr - (DeptName)
Here is the code I am using to do this and it works fine:
<telerik:RadComboBox ID="rcbDepartments" runat="server" AppendDataBoundItems="True"
OnInit="rcbDepartments_Init" DataTextField="DepartmentAbbr" AutoPostBack="True"
DataSourceID="ldsDepartments" DataValueField="DepartmentID" HighlightTemplatedItems="true"
NoWrap="true" Width="250px">
<ItemTemplate>
<div>
<b>
<%# Eval("DepartmentAbbr")%></b><%# Eval("DepartmentName", " - ({0})") %>
</div>
</ItemTemplate>
</telerik:RadComboBox>
My question is this. I want to add an initial item in the list that is for "All Departments" and is the default item. I can do this easily, but the problem I'm having is that because I am not storing an "All Departments" entry in the database, the templating shows a blank space at the beginning of the items list when you pull down the combo box. I'm trying to find out if there is any way to template all but first item in the list?
Note: I have also tried do a conditional in the Eval like this:
<b><%# (Eval("DepartmentAbbr") != null) ? Eval("DepartmentAbbr") : "All Departments" %></b><%# Eval("DepartmentName", " - ({0})") %>
But it only evaluates on the items that are databound and not the initial item which I am sticking in manually. In other words, if I change the above statement to be:
<b><%# (Eval("DepartmentAbbr") == null) ? Eval("DepartmentAbbr") : "All Departments" %></b><%# Eval("DepartmentName", " - ({0})") %>
Then I just get a list with one blank item at the top and the rest reading "All Departments".
My work around for this problem has been to do some funky selection stuff with LINQ server side, but that has forced me to get rid of all templating and html formatting.
You can define the 'All Departments' RadComboBoxItem as a static item in the <Items> collection. Since you have enabled the AppendDataBoundItems property, you don't want to bind to your data source until after the control has already bound the static items; otherwise you'll get the blank space you are seeing when expanding the combo box. Also, use DataBinder.Eval(Container, "Text") to render the DepartmentAbbr field. Since you have set this field as the DataTextField for the control, that value will always render. If not, you'll get the empty space again when the control binds to the static item because it doesn't know what DepartmentAbbr is; it only has a Text field. Here's an example to get you going:
<telerik:RadComboBox ID="RadComboBox1" runat="server"
AppendDataBoundItems="True"
DataTextField="Abbr"
AutoPostBack="True"
DataValueField="DeptID"
HighlightTemplatedItems="true"
NoWrap="true"
Width="250px">
<Items>
<telerik:RadComboBoxItem runat="server" Text="All Departments" />
</Items>
<ItemTemplate>
<div>
<b><%# DataBinder.Eval(Container, "Text")%></b><%# Eval("Name", " - ({0})") %>
</div>
</ItemTemplate>
</telerik:RadComboBox>
public partial class _Default : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
RadComboBox1.Load += new EventHandler(RadComboBox1_Load);
}
protected void RadComboBox1_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Ensure the static items are already bound before assigning
// new data to the DataSource property
RadComboBox1.DataBind();
var departments = new[] {
new { DeptID = 1, Abbr = "ACME", Name = "ACME Corporation" },
new { DeptID = 2, Abbr = "MSFT", Name = "Microsoft Corporation" },
new { DeptID = 3, Abbr = "GOOG", Name = "Google, Inc" }
};
RadComboBox1.DataSource = departments;
RadComboBox1.DataBind();
}
}
}
Hope that helps!

Resources