Get List of DataKeyValues from RadGridView using LINQ - c#

I'm using a Telerik RadGrid and have a GridTemplateColumn with the unique name "ChangeAddr". Basically, a user would check one or more boxes and then click a "Change Address" button so the user could change the address for the selected rows/products.
The checkbox id is chkChangeAddr.
The DataKeyName is OrderProductID.
Now, here's the code I have for when the user clicks the button:
var OrderProductIDs = (from GridDataItem item in rgShipProducts.Items
where ((CheckBox)item.FindControl("chkChangeAddr")).Checked
select int.Parse(rgShipProducts.MasterTableView.DataKeyValues[item.ItemIndex]["OrderProductID"].ToString())).ToList();
However, it doesn't return anything.
If it helps, I have an event for OnItemDataBound where I can successfully retrieve the DataKeyValue using this same snippet:
rgShipProducts.MasterTableView.DataKeyValues[item.DataSetIndex]["OrderProductID"].ToString()
So, it seems like I'm not "accessing" each item or something. I've done this with regular ListViews, but never on a RadGrid. Any help would be greatly appreciated.
Thanks,
Andrew

try with below code.
List<GridDataItem> Items = (from item in rgShipProducts.MasterTableView.Items.Cast<GridDataItem>()
where ((CheckBox)item.FindControl("chkChangeAddr")).Checked
select item).ToList();
if (Items.Count > 0)
{
string strkey = Items[0].GetDataKeyValue("ID").ToString();
}

Related

Selecting Multiple ListBox items from GridView column

I have a databound Listbox with Multiselect enabled. On page load, I feed the information from a GridView column and select all the options that match, using this code:
string[] separators = { "<br />" };
String Departments = Session["ProjDept"].ToString();
string[] splitDepartments = Departments.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var dept in splitDepartments)
{
listDepartment.SelectedIndex = listDepartment.Items.IndexOf(listDepartment.Items.FindByText(dept));
}
However, I am running into a strange issue: when there is only one department in the GridView column, the option in the listbox gets properly selected, but when there's multiple departments only the LAST department gets selected.
I've ran System.Diagnostics.Debug.Print(dept) within my foreach to ensure that all the values are getting passed and they all appear in the STDOUT, but the listbox still won't cooperate.
Any ideas as to how I can fix this -- or alternatively, what other code could I use to achieve the same results?
Thank you!
The SelectedIndex property only allows one value at a time, so you're resetting it with each iteration. That's why only the last one is being selected. You need to access the "Selected" property from the ListItem itself.
Without trying it myself, it should look something like:
foreach (var dept in splitDepartments)
{
int index = listDepartment.Items.IndexOf(listDepartment.Items.FindByText(dept));
listDepartment.Items[index].Selected = true;
}
As long as you do have SelectionMode="Multiple" - that code should work.

How to select an Item from asp:Dropdownlist on Page load from Code Behind C#?

I tried so many articles around, like below to get my task done, but didn't work as I always ends up with an NullReferenceException, I have bound a database table column to the Dropdown list, on page load i want to select an item based on the value from database which is one of those listed items. Please help me.
txt_examtype.DataSource = dt;//txt_examtype is the dropdownlist
txt_examtype.DataTextField = "ExamTypeName";
txt_examtype.DataValueField = "ExamTypeName";
txt_examtype.DataBind();
String examtype = dt.Rows[0]["ExamType"].ToString().Trim();
ListItem myitem = txt_examtype.Items.FindByValue(examtype);
txt_examtype.SelectedValue = myitem.Value;
try this code
txt_examtype.SelectedValue = dt.Rows[0]["ExamType"].ToString()
You should set SelectedIndex instead of SelectedValue. This is safe to use:
txt_examtype.SelectedIndex = txt_examtype.Items.IndexOf(txt_examtype.Items.FindByValue(examtype));

Search within Datagrid and scroll & select newly added item

I'm using the Telerik Datagrid control to display 100's of records. In my app the user selects a they want to edit and I use a form to allow the user to update the record.
Likewise, if they wish to add a new record they click 'Add' and a blank version of the form appears.
I'm not binding direct to a data source. I'm providing the data to the grid by setting the Itemsource to my List of records.
When the user has edited a record I can scroll and select the edited record quite easily:
//find row index of selected item
var lastRowUpdated = RadGridAssetTable.Items.IndexOf(this.RadGridAssetTable.SelectedItem);
// move to index following edit
RadGridAssetTable.ScrollIndexIntoView(lastRowUpdated);
RadGridAssetTable.SelectedItem = lastRowUpdated;
However, when I add a new record I cannot figure out how to programmatically scroll and select the newly added grid item.
Effectively I want to search the grid rows for the (hidden) record ID, select the row index in the control and scroll to it
There doesn't appear to be a way of searching data in the grid programmatically, can someone point in the correct direction on how to do this?
Regards
Ok, so I solved like this.
var lastRowUpdated = 0;
var i = 0;
if (_assetsavedData.AssetId == -1)
{
foreach (var rowItem in from object row in RadGridAssetTable.Items select row as AssetLinked)
{
Debug.WriteLine(rowItem.AssetItems.AssetCommonName);
if (rowItem.AssetItems.AssetCommonName.Equals(_assetsavedData.AssetCommonName))
{
lastRowUpdated = i;
Debug.WriteLine("found at " + i);
break;
}
i++;
}
}
else
{
lastRowUpdated = RadGridAssetTable.Items.IndexOf(this.RadGridAssetTable.SelectedItem);
}

grid view search using dropdown list and text box filter?

Sir/madam now my problem is this that I want to filter the Grid View of a page using a Drop Down list and a text box.
I mean to say like we write a SQL such as:
Select * from student where roll_no = 101;
Right,
Now I what that the column (roll_no in above statement) should be selected by the drop down list and the value (101 in the above statement) should be entered by the Text box.
In short I want to populate my grid view using Drop Down list and the value of text box by clicking a button..
For developing i am using dataset and table adapters.
Please, help me for this..
I use a drop-down list (combo-box) and a textbox to filter my DataGridView the following way and I think this is what you are looking for.
First, populate your DataGridView. You state you are using a DataSet and TableAdapters. I am guessing that you are using a BindingSource to tie your Data to your DataGridView. If that is the case, then you can Filter your data via the BindingSource.
My set up is similar to this:
My combobox contains the fields that I want to use in my Filter and the textbox is the value that I will be applying. The values in the combobox are user-friendly names so they will understand which field they are filtering on.
The code to apply the filter is:
private void ApplyFilter()
{
var filterEntered = FilterTextBox.Text.Trim().ToLower();
MyBindingSource.RemoveFilter(); // remove previous filter
string filterText = string.Empty;
string filterComboText = string.Empty;
switch (FilterComboBox.Text)
{
case "Profile":
filterComboText = "TSProfile"; // column name in the query
break;
case "User Id":
filterComboText = "TSUserId";
break;
case "Center":
filterComboText = "TSCenter";
break;
case "Prefix":
filterComboText = "TSPrefix";
break;
}
filterComboText = filterComboText + " = '";
filterText += (string.IsNullOrEmpty(filterComboText) ? string.Empty : filterComboText);
filterText += (!string.IsNullOrEmpty(filterText) && !string.IsNullOrEmpty(filterEntered) ? filterEntered + "'" : string.Empty);
MyBindingSource.Filter = filterText;
}
Basically what it is doing, is getting the text name of the combo-box and then the text in the textbox and applying the Filter to the BindingSource.
MSDN has an article on Filtering thats contains full sample code.
The one thing that I recommend is to provide the user with a way to easily remove the filter, I use a Remove Filter button.
it would be helpful if you showed us a little code first..
you could try something like this tho:
in your codebehind, add items to your dropdownlist.
List<yourObject> list = new List<yourObject>();
foreach (yourObject i in list)
{
DropdownList1.Items.Add(new ListItem("" i.name, "" + i.id));
}
im just giving an example here, i.name could be the name of a certain student, i.id would be the id associated with that given student.
Make sure you have the autopostback attribute of your dropdownlist set to true, like this:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
Then in the selected Index Changed event of your dropdownlist, do the following:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
yourDataControl.DataSource = someMethod(Convert.toInt32(DropDownList1.SelectedValue));
yourDatacontrol.DataBind();
}
as i said, im not entirely sure what you're trying to do or how you're trying to do it.
the way i'm describing, you dont need the textbox to enter a certain value, by selecting an item in the dropdownlist you wil automatically get a value: in this case the ID associated with the selected item in the dropdownlist.

Telerik getting selected ID (Get data from Radgrid selected item)

I can get the selected index of the gridview but i want to get the actual data that is inside the grid. I want to select a row in the grid and be able to access the "Client Id" column's actual data value. The grid is working fine and I am able to access the SelectedIndexChanged event. I have then been trying with no luck to find a way to get the information that is displayed in the grid. Any help would be greatly appreciated.
Again, I need to get access to all data that is displayed in the grid form the codebehind.
This is what data keys are for. Just designate the columns you want to access as data keys, like in the example shown below.
<telerik:RadGrid ID="RadGrid1" runat="server" ...>
<MasterTableView DataKeyNames="Column1, Column2, Column3" ...>
...
</MasterTableView>
</telerik>
Once the data keys have been assigned in the markup, you can access them in code-behind by row, or using the SelectedValues property.
if (RadGrid1.SelectedItems.Count > 0)
{
//access a string value
string column1 = RadGrid1.SelectedValues["Column1"].ToString();
//access an integer value
int column2 = (int)RadGrid1.SelectedValues["Column2"];
}
You could do it like this:
foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
{
if (item.selected == true)
string mydata = item["ColumnName"].Text;
}
I recommend you read the documentation on this site http://www.telerik.com/help/aspnet/grid/grdaccessingcellsandrows.html; it will sure help you a lot with Telerik components.
Use DataKeys as James Johnson suggested. You cannot access DataItem property of the GridDataItem in SelectedIndexChanged event. It will be null. According to Telerik documentation "DataItem object is available only when grid binds to data."
When DateItem is available, as in the ItemCreated event, you could do a cast to your original data type MyType:
private void RadGrid_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if ((e.Item is GridDataItem)) {
GridDataItem gridDataItem = (GridDataItem)e.Item;
MyType dataItem = (MyType)gridDataItem.DataItem;
}
}

Categories

Resources