I have an ASPxGridView and in the EditForm, I have a popup form when the suer clicks a button. I need to get the ID for the currently selected entity/row so that I can query the db and populate a dropdown on the popup based on that ID. How can I get that? I know with some events, you can do this:
protected void myGrid_OnRowUpdating(object sender, ASPxDataUpdatingEventArgs e)
{
Guid entityId = (Guid)e.Keys[0];
So I wanted to try that with the SelectionChanged event, but the event argument is only of type EventArgs, so i cannot use the above..
Ideas?
You can use the HtmlRowCreated event to bind the contents of the dropdown as shown below.
protected void myGrid_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
{
if (e.RowType != GridViewRowType.EditForm)
return;
var grid = sender as ASPxGridView;
if (grid == null)
return;
var row = (sender as ASPxGridView).GetRow(e.VisibleIndex) as MyEntity;
var ddlMyDropDown = grid.FindEditFormTemplateControl("ddlMyDropDown") as ASPxComboBox;
ddlMyDropDown.DataSource = GetDataForMyDropdown(); // Your Business Logic
ddlMyDropDown.DataBind();
}
I ended up doing something client-side. First, I added this column:
<dx:GridViewCommandColumn ShowSelectCheckbox="True" VisibleIndex="0" Width="40">
<HeaderTemplate>
<dx:ASPxCheckBox ID="SelectAllCheckBox" runat="server" ToolTip="Select/Unselect all rows on the page"
ClientSideEvents-CheckedChanged="function(s, e) { gridView.SelectAllRowsOnPage(s.GetChecked()); }" />
</HeaderTemplate>
</dx:GridViewCommandColumn>
then I also added this (to the same grid):
<ClientSideEvents SelectionChanged="grid_SelectionChanged" />
Lastly, the javascript:
var selected = [];
function grid_SelectionChanged(s) {
s.GetSelectedFieldValues("ID", GetSelectedFieldValuesCallback);
}
function GetSelectedFieldValuesCallback(values) {
selected = [];
for (var i = 0; i < values.length; i++) {
selected.push(values[i]);
}
}
Related
I have a RadGrid that I supply with data using DataSourceID. The RadGrid has paging, and I want to show the page containing some particular item. To do this, I find the offset of the item in the data and set the page number:
var index = dataSource.Count(t => t.Id > _selectedTickId);
var page = index / rgTicks.PageSize;
rgTicks.CurrentPageIndex = page;
My question is where to put this code. In the OnDataBound I don't seem to have access to the data source. If I put it in the OnSelecting the retrieving of data has a side effect of setting the page number. Should I extend the GridTableView to implement this functionality? Which method should I override?
I will suggest to compute index value in OnSelecting (which is data dependent) while page index can be set in OnDataBound or PreRender event.
My usecase was to jump to an item that was just inserted using a popup editor. Here's how I solved it. I am omitting non relevant properties in the tag. All the data wiring is up to you, but here are the relevant bits. Important: use DataKeyNames to avoid messy digging in the GridDataItem for a value.
In the page I have:
<telerik:RadGrid ID="rgItems" runat="server" AllowPaging="true"
OnNeedDataSource="rgItems_NeedDataSource"
OnPreRender="rgItems_PreRender"
OnInsertCommand="rgItems_InsertCommand">
<MasterTableView
CommandItemDisplay="Top"
CommandItemSettings-AddNewRecordText="Add New Item"
CommandItemSettings-ShowAddNewRecordButton="True"
DataKeyNames="IntItemId"
EditMode="popup"
EditFormSettings-PopUpSettings-Modal="true">
And in code behind:
private bool itemInserted = false;
protected void rgItems_InsertCommand(object sender, GridCommandEventArgs e)
{
itemInserted = true;
}
protected void rgItems_PreRender(object sender, EventArgs e)
{
if (itemInserted)
{
// Select the record and set the page
int LastItem = 0; // Put code to get last inserted item here
int Pagecount = rgItems.MasterTableView.PageCount;
int i = 0;
GridDataItem GDI = null;
while (i < Pagecount)
{
rgItems.CurrentPageIndex = i;
rgItems.Rebind();
GDI = rgItems.MasterTableView.FindItemByKeyValue("IntItemId", LastItem);
if (GDI != null) break; // IMPORTANT: Breaking here if the item is found stops you on the page the item is on
i++;
}
if (GDI != null) GDI.Selected = true; // Optional: Select the item
itemInserted = false;
}
}
i have a datalist contains checkboxlist.
<asp:DataList ID="dtlstfilter" runat="server">
<ItemTemplate>
<asp:CheckBoxList ForeColor="Gray" AutoPostBack="true" OnSelectedIndexChanged="chklist_SelectedIndexChanged" ID="chklist"
runat="server">
</asp:CheckBoxList>
</ItemTemplate>
</asp:DataList>
when i check one from the checkbox list in the SelectedIndexChanged event i got the selected value using
CheckBoxList c = (CheckBoxList)sender;
string selectedvalue= c.SelectedValue;
likewise how can get the value from a checkboxlist if i uncheck one from the checkboxlist
The SelectedIndexChanged gets also fired if you uncheck a CheckBox. So it works the same way. But if you want to know the (now) unchecked item(s), you have to store the old selection somewhere, for example in the ViewState:
private IEnumerable<string> SelectedValues
{
get
{
if (ViewState["SelectedValues"] == null && dtlstfilter.SelectedIndex >= -1)
{
ViewState["SelectedValues"] = dtlstfilter.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();
}else
ViewState["SelectedValues"] = Enumerable.Empty<string>();
return (IEnumerable<string>)ViewState["SelectedValues"];
}
set { ViewState["SelectedValues"] = value; }
}
protected void chklist_SelectedIndexChanged(Object sender, EventArgs e)
{
CheckBoxList c = (CheckBoxList)sender;
var oldSelection = this.SelectedValues;
var newSelection = c.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value);
var uncheckedItems = newSelection.Except(oldSelection);
}
This should even work if multiple checkboxes can be selected.
You can take the jQuery Route if it suits you...
if (!IsPostBack)
{
foreach (ListItem item in chkList.Items)
{
//adding a dummy class to use at client side.
item.Attributes.Add("class", "chkItem");
}
}
Put one button on your form with style display : none. And a Hidden Field to track the currently checked checkbox.
<asp:Button ID="hdnButton" runat="server" style="display:none;" OnClick="hdnButton_Click"/>
<asp:HiddenField ID="hdnCurrent" runat="server" />
The jQuery Part....
$(".chkItem input:checkbox").change(function(){
$("#hdnCurrent").val($(this).attr("id") + "|" + $(this).attr("checked"));
$("#hdnButton").click();
});
You can use more hidden fields if you don't want to do string operations on backend. Depends on your taste.
Then handle the button click event like below.
protected void hdnButton_Click(object sender, EventArgs e)
{
String[] Value = hdnCurrent.Value.Split('|');
if (Value[1] == "true")
{
//Do operations here when the check box is checked
}
else
{
//Do operations here when the check box is unchecked
}
//Value[0] contains the id of the check box that is checked/unchecked.
}
How do I determine if the checkbox is checked or not checked?
Very perplexed why this is not working - it is so simple!
On my web form:
<asp:CheckBox ID="DraftCheckBox" runat="server" Text="Save as Draft?" />
<asp:Button ID="PublishButton" runat="server" Text="Save" CssClass="publish" />
Code behind which runs in the click event for my save button:
void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
}
When debugging it never steps into the If statement when I have the checkbox checked in the browser. Ideas?!
I think there maybe some other code affecting this as follows...
In Page_load I have the following:
PublishButton.Click += new EventHandler(PublishButton_Click);
if (newsItem.IsDraft == 1)
{
DraftCheckBox.Checked = true;
}
else
{
DraftCheckBox.Checked = false;
}
newsItem is my data object and I need to set the checkbox checked status accordingly.
When the save button is hit I need to update the IsDraft property based on the checked status of the checkbox:
void PublishButton_Click(object sender, EventArgs e)
{
if (IsValid)
{
newsItem.Title = TitleTextBox.Text.Trim();
newsItem.Content = ContentTextBox.Text.Trim();
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
else
{
newsItem.IsDraft = 0;
}
dataContext.SubmitChanges();
}
}
So, isDraft = 1 should equal checkbox checked, otherwise checkbox should be un-checked. Currently, it is not showing this.
Specify event for Button Click
<asp:Button ID="PublishButton" runat="server" Text="Save" onclick="PublishButton_Click" />
What i can see you have not got a OnClick on your button. So like this:
<asp:CheckBox ID="DraftCheckBox" runat="server" Text="Save as Draft?" />
<asp:Button ID="PublishButton" runat="server" OnClick="PublishButton_Click"
Text="Save" CssClass="publish" />
And then the function should work like it is:
protected void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked)
{
newsItem.IsDraft = 1;
}
}
Please replace code as following code..
void PublishButton_Click(object sender, EventArgs e)
{
if (DraftCheckBox.Checked==True)
{
newsItem.IsDraft = 1;
}
}
Try adding onclick="PublishButton_Click" in the button field on the form. And I don't know if it makes a difference, but generated event handlers are protected void.
For me the best solution in the end has been to create 2 separate pages: 1 for editing a news articles & 1 for a new news article. So Ill never then be in the position of a new news data object being created when the page reloads.
Both page return to the article index list page when the save button is pressed and that seems to work with being able to save the state of the draft checkbox and then show the state on the edit page.
The checkbox.checked isn't used in the context you want it to (this is a boolean that if true, will make the checkbox look checked).
What you could do is to use instead a checkboxlist. Then you could do the following:
foreach(Listitem li in CheckBoxList1.Items)
{
if (li.Selected)
{
NewsItem.Isdraft = 1;
}
}
I am currently highlighting a row in a radgrid using OnMouseOver. I would like to know if it is possible to use OnMouseOver to select the row rather than highlight it.
Alternatively, I would like the highlighted row to remain highlighted if the radgrid loses focus, such as when a confirmation box pops up.
Thanks in advance.
According to Telerik documentation, it should be possible to select the item OnMouseOver using the following code (if you don't have any detail tables you can nix the if statement and just use the code from the else block to find the currentDataItem):
function RadGrid1_RowMouseOver(sender, eventArgs) {
var currentDataItem = null;
// clear all currently selected items before selecting new
sender.get_masterTableView().clearSelectedItems();
if (eventArgs.get_itemIndexHierarchical().indexOf(':') > 0)
{
var detailTableIndex = eventArgs.get_itemIndexHierarchical().split(':')[0];
var rowIndex = eventArgs.get_itemIndexHierarchical().split(':')[1].split('_')[1];
currentDataItem = sender.get_detailTables()[detailTableIndex].get_dataItems()[rowIndex];
}
else
{
currentDataItem = sender.get_masterTableView().get_dataItems()[eventArgs.get_itemIndexHierarchical()];
}
if (currentDataItem != null)
{
currentDataItem.set_selected(true);
}
}
The other answers here do not work with the WPF Telerik RadGridView as we don't have access to RowMouseOver event.
For a WPF Telerik RadGridView, the best approach if the grid doesn't contain UI elements is to use ChildrenOfType<> in a Linq expression with IsMouseOver.
private void myGridView_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
MyCustomClass myClass = null;
var rows = this.myGridView.ChildrenOfType<GridViewRow>().Where(r => r.IsMouseOver == true);
foreach (var row in rows)
{
if (row is GridViewNewRow) break;
GridViewRow gvr = (GridViewRow)row;
myClass = (MyCustomClass)gvr.Item;
}
// do something with myClass here if we have found a row under mouse
}
Thanks! Your solution worked great, but rows would not become unselected when mousing over another row even if AllowMultiRowSelection was set to False. The following code will select a single row in the radgrid when the mouse hovers over the row:
<script type="text/javascript">
function grdUsers_RowMouseOver(sender, eventArgs) {
var NumberItems = sender.get_masterTableView().get_dataItems().length;
for (var count = 0; count < NumberItems; count++) {
var currentDataItem = sender.get_masterTableView().get_dataItems()[count];
if (count == eventArgs.get_itemIndexHierarchical()) {
currentDataItem.set_selected(true);
}
else {
currentDataItem.set_selected(false);
}
}
}
</script>
I called the function at the following location:
<ClientSettings AllowColumnsReorder="True" ReorderColumnsOnClient="True">
<Selecting AllowRowSelect="True" />
<ClientEvents OnRowMouseOver="grdUsers_RowMouseOver" />
</ClientSettings>
I have to set a LinkButton's OnClientClick attribute but I don't know what this value is until the LinkButton is bound to. I'm trying to set the value when the repeater binds, but I can't workout how to get the 'boundItem/dataContext' value...
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton Text="HelloWorld" ID="Hyper1" runat="server" OnDataBinding="Repeater1_DataBinding" >
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<TestObject>();
list.Add(new TestObject() {TestValue = "testing1"});
list.Add(new TestObject() { TestValue = "testing2" });
list.Add(new TestObject() { TestValue = "testing3" });
this.Repeater1.DataSource = list;
this.Repeater1.DataBind();
}
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
//link.DataItem ???
}
Is there anyway to find out what the current rows bound item is?
Maybe you need to use ItemDataBound event. It provides RepeaterItemEventArgs argument which has DataItem available
this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem;
}
I assume you are trying to get the value for the row that is currently being databound?
You can change your function to:
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
string valueYouWant = Eval("TestValue").ToString();
// You could then assign the HyperLink control to whatever you need
link.Target = string.Format("yourpage.aspx?id={0}", valueYouWant);
}
valueYouWant now has the value of the field TestValue for the current row that is being databound. Using the DataBinding event is the best way to do this compared to the ItemDataBound because you don't have to search for a control and localize the code specifically to a control instead of a whole template.
The MSDN library had this as a sample event handler:
public void BindData(object sender, EventArgs e)
{
Literal l = (Literal) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView) container.DataItem)[column].ToString();
}
(see http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx)
As you can see it is a simple demonstration of how to access the data item and get data from it. Adapting this to your scenario is an exercise left to the reader. :)