Telerik Radgrid How to retrieve textbox values from dynamically generated RadGrid columns? - telerik-grid

I am dynamically creating a RadGrid and adding GridTemplateColumns to it. Those columns have textbox in them.
After binding datatable to the grid, after user makes changes to the textboxes and on clicking save button, I would like to access the textbox values. But I am stuck at getting hold of the textbox instance. I couldn't even get hold of GridItems!
To add more complexity, my RadGrid is in a UserControl, which is in a (multi)view.
Heres the code.
protected void Page_Init(object sender, EventArgs e)
{
DefineGridStructure();
}
protected void Page_Load(object sender, EventArgs e)
{
if (RadGrid1 != null && RadGrid1.Items.Count > 0)
{
string strtxt = ((TextBox)RadGrid1.Items[1]["ProductGroup1"].Controls[0]).Text;//For starters, load one control and check it's state
}
}
private void DefineGridStructure()
{
RadGrid1 = new RadGrid();
RadGrid1.AutoGenerateColumns = false;
RadGrid1.ShowHeader = true;
RadGrid1.NeedDataSource += RadGrid1_NeedDataSource;
foreach(GridColumn qtyColumn in BuildGridQtyColumns(PaxColumnCount))
{
RadGrid1.MasterTableView.Columns.Add(qtyColumn);
}
//Add grid to page
phRadGrid.Controls.Add(RadGrid1);
}
private List<GridColumn> BuildGridQtyColumns(int count)
{
List<GridColumn> qtyColumns = new List<GridColumn>();
for (int i = 1; i <= count; i++)
{
string qtyColumnName = string.Format("ProductGroup{0}", i);
GridTemplateColumn qtyColumn = new GridTemplateColumn();
qtyColumn.ItemTemplate = new GridNumberTemplate(qtyColumnName);//Creates a textbox control
qtyColumn.UniqueName = qtyColumnName;
qtyColumn.HeaderText = "Qty";
qtyColumn.HeaderStyle.Width = Unit.Pixel(60);
qtyColumn.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
qtyColumns.Add(qtyColumn);
}
return qtyColumns;
}
Since my control is in view, it's Page_Init is called more than once for each action that involves this view.

For a dynamically generated radgrid, it should be created in page_init method and viewstate for this grid will be restored for us automatically which we can get hold of in page_load method.

Related

Insert a grid line when the record gets saved

I am trying to add a new record to a grid during the persist logic. However, even though the record does get added to the grid in the UI, when the page gets refreshed, the new line disappears. It is not getting persisted in the DB.
I am using the Bills page as reference.
Code sample
protected virtual void APTran_RowPersisting(PXCache sender, PXRowPersistingEventArgs e)
{
if (e.Row == null)
{
return;
}
APInvoice invoiceRow = this.Base.Document.Current;
if (invoiceRow != null)
{
APTran tranRow = new APTran();
tranRow = this.Base.Transactions.Insert(tranRow);
tranRow.InventoryID = 10043;
this.Base.Transactions.Update(tranRow);
tranRow.Qty = 3;
this.Base.Transactions.Update(tranRow);
}
}
Result after saving - Record is shown in the grid:
Result after cancelling - Record disappears from the grid:
Something like this I tend to override the Persist method and insert or update related records before calling base persist. Here is a possible example which goes inside your graph extension:
[PXOverride]
public virtual void Persist(Action del)
{
foreach(APInvoice invoiceRow in Base.Document.Cache.Inserted)
{
APTran tranRow = this.Base.Transactions.Insert();
tranRow.InventoryID = 10043;
tranRow = this.Base.Transactions.Update(tranRow);
tranRow.Qty = 3;
this.Base.Transactions.Update(tranRow);
}
del?.Invoke();
}

What's the proper way to edit text in objectlistview

I have an objectlistview with 4 columns and a dynamic number of rows, I'm struggling with programmable editing a cell text value, and optionally change the forecolor
I've read everything and anything that I could put my hands on, but couldn't find any valid and right to the point example on how to do it.
the ObjectListView is created this why
List<VideoItem> list = new List<VideoItem>();
foreach (dynamic item in VideoItems)
{
list.Add(new VideoItem { Index = (int)item.index, OldName = (string)item.oldname, NewName = (string)item.newname });
}
olv1.AddObjects(list);
VideoItem class look like this
private class VideoItem
{
public int Index;
public string OldName;
public string NewName;
}
but i need to programmably edit a cell text on event. I'm doing some logical operations on other cell at the end im storing the result to to cell next to it.
You should be storing the result (making the change) to the underlying model object and then call RefreshObject(myModelObject);
About the forcolor, i need to change only the cell I've changed
"To change the formatting of an individual cell, you need to set UseCellFormatEvents to true and then listen for FormatCell events."
Take a look at this.
Just to add to Rev1.0 Answer, i needed to update the object that contains the items (in my case a List) then, use olv1.RefreshObject(list); flow by olv1.BuildList(true);
the olv1.BuildList(true); refresh the GUI immediately.
here a small code snippet to make thing bit more clear
it's changing the data in column 3 when a checkbox is checked.
using System.Collections.Generic;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Initializeolv();
}
private class VideoItem
{
public int Index;
public string OldName;
public string NewName;
}
private List<VideoItem> list = new List<VideoItem>();
private void Initializeolv()
{
for (var i = 1; i <= 10; i++)
{
list.Add(new VideoItem { Index = i, OldName = $"old{i}", NewName = $"new{i}" });
}
olv1.AddObjects(list);
}
private void olv1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
list[e.Item.Index].NewName = "new200";
olv1.RefreshObject(list);
olv1.BuildList(true);
}
}
}

Clear All TextBoxes Inside User Control

So I have a user control with six textboxes and a few buttons. One of those buttons is 'clear'. When I click the clear button, in the btnClear_Click handler, I want to find all the textboxes in my user control (and ONLY in my user control). And then set them to an empty string. That's it. That's all.
This is turning out to be a herculean, insurmountably difficult thing to do. Finding an answer is like trying to map the human genome. I just want to ITERATE THROUGH THE CONTROLS. Nothing more.
I'm not interested in hearing about the merits of what I'm trying to do. Just the mechanics of how to do it. Something like this:
public partial class myUserControl: UserControl
{
private void btnClear_Click(object sender, RoutedEventArgs e)
{
var allMyControls = SomeMiraculousOperationToGetAllControlsThatOnlyExistInMyUserControl();
foreach (var control in allMyControls)
{
if (control is TextBox)
((TextBox)control).Text = string.Empty;
}
}
}
You can use the VisualTreeHelper to enumerate the child controls of your user control.
You can find an extension method base on this class here
public static T GetChildOfType<T>(this DependencyObject depObj)
where T : DependencyObject
{
if (depObj == null) return null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
var result = (child as T) ?? GetChildOfType<T>(child);
if (result != null) return result;
}
return null;
}

Select a row on mouse click in gridview

I have a problem, I want to select a row in gridview on mouse click.
My code is this :
protected void PeopleGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvdetails, "Select$" + e.Row.RowIndex);
}
}
it is not working. i don't know why?
plz suggest me regarding that.
"Thanks"
Found the tutorial about ASP.Net select row in gridview
In ASPX page under GridView tag add:
<SelectedRowStyle BackColor="Orange" />
In code behind try the following:
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
foreach (GridViewRow row in PeopleGridView.Rows) {
if (row.RowType == DataControlRowType.DataRow) {
row.Attributes["onmouseover"] =
"this.style.cursor='hand';this.style.textDecoration='underline';";
row.Attributes["onmouseout"] =
"this.style.textDecoration='none';";
// Set the last parameter to True
// to register for event validation.
row.Attributes["onclick"] =
ClientScript.GetPostBackClientHyperlink(PeopleGridView,
"Select$" + row.DataItemIndex, true);
}
}
base.Render(writer);
}
You can then catch this event using the RowCommand (something like).
private void PeopleGridView_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "Select") {
// Get the list of customers from the session
List<Customer> customerList =
Session["Customers"] as List<Customer>;
Debug.WriteLine(customerList[Convert.ToInt32(e.CommandArgument)].LastName);
}
}

Preventing TabControl selection in Silverlight

Is there any way to prevent the change of a tab in TabControl in Silverlight 4?
A simple case is when I've got a form with some data, and I want to ask the user if he/she wants to save this data before actually changing the tab.
I've seen code examples on how to do this in WPF, but not in Silverlight.
What can I do to stop the tab from changing?
Bind SelectedIndex to a property on your data context.
<sdk:TabControl SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}">
<sdk:TabItem Header="TabItem">
<Grid Background="#FFE5E5E5"/>
</sdk:TabItem>
<sdk:TabItem Header="TabItem">
<Grid Background="#FFE5E5E5"/>
</sdk:TabItem>
</sdk:TabControl>
In the SET accessor, write your code to check whether the user really wants to do what they're trying to do.
public class Context : INotifyPropertyChanged
{
int _SelectedIndex = 0;
public int SelectedIndex
{
get
{
return _SelectedIndex;
}
set
{
MessageBoxResult result = MessageBox.Show("Do you want to save?", "Really?", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
_SelectedIndex = value;
}
RaisePropertyChanged("SelectedIndex");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
Net effect is, if the user chooses 'cancel' on the dialogue the private variable is never changed - the PropertyChanged event fires, rebinding the selected index to the existing value.
Hope this is what you were trying to accomplish.
UPDATE (11/10/2012) - Alternate method (possibly for SL5?). Write code behind to tie into SelectionChanged event of your TabControl, reset the tab control's selected item property based on your test.
private void TabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (e.RemovedItems.Count > 0)
{
MessageBoxResult result = MessageBox.Show("Do you want to save?", "Really?", MessageBoxButton.OKCancel);
if (result != MessageBoxResult.OK)
{
((TabControl)sender).SelectionChanged -= new SelectionChangedEventHandler(TabControl_SelectionChanged);
((TabControl)sender).SelectedItem = e.RemovedItems[0];
((TabControl)sender).SelectionChanged += new SelectionChangedEventHandler(TabControl_SelectionChanged);
}
}
}

Resources