How Can I get Cell Values from Telerik RadGrid - telerik

I am having a problem getting the values from the Radgrid auto generated Insert form.
I have my radgrid setup as shown in code shown below. I am only doing inserts and deletes and am using the edit form that is automatically opened when I click the add new record button.
<div id ="specialrequestGrid" class="container">
<div class="row">
<div class="col-md-12">
<telerik:RadAjaxPanel runat="server">
<telerik:RadGrid ID="SpecialRequests" runat="server" OnInsertCommand="SpecialRequests_InsertCommand"
OnUpdateCommand="SpecialRequests_UpdateCommand"
OnItemCommand="SpecialRequests_ItemCommand"
AllowAutomaticInserts="false"
AutoGenerateColumns="false"
OnNeedDataSource="SpecialRequests_NeedDataSource">
<MasterTableView CommandItemDisplay="Top" DataKeyNames="CaseId_FK, ReqId" Font-Size="Medium" NoMasterRecordsText="No Special Requests">
<CommandItemSettings AddNewRecordImageUrl="../Images/Add.png" />
<Columns>
<telerik:GridTemplateColumn HeaderText="Request Date" UniqueName="DateTemplateColumn">
<ItemTemplate>
<asp:Label ID="DateEditItemTemplate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Date","{0:MM/dd/yyyy}") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadDatePicker ID="dpRideDate" runat="server" DateInput-DateFormat="MM/dd/yyyy" DbSelectedDate='<%# Bind("Date") %>' MinDate="1999/1/1" UniqueName="dpRideDate">
</telerik:RadDatePicker>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Requested By ID" UniqueName="RequestorTemplateColumn">
<ItemTemplate>
<asp:Label ID="Requestor" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "RequesterEID_FK") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<button id="btnRequestEID" type="button" class="btn" data-toggle="modal" data-target="#myModal" >--Please Select--</button>
<div>
<input type="text" Id="TxtSPRequestName" disabled />
</div>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Request Reason" UniqueName="RequestReason">
<ItemTemplate>
<asp:Label ID="ItemTemplatelblRequestReason" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Reason") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblRequestReason" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Reason") %>' Visible="false">
</asp:Label>
<asp:TextBox runat="server" ID="txtReason" Text='<%# DataBinder.Eval(Container.DataItem, "Reason") %>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridCheckBoxColumn DataField="IsWOO" HeaderText="Is Out of Order" UniqueName="ISWOO"></telerik:GridCheckBoxColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</div>
</div>
</div>
This is the screenshot of the auto generated form I get when I click the add new record
When I click the Insert link on the form I run this C# code
protected void SpecialRequests_InsertCommand(object sender, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
T_SpecialRequests t = new T_SpecialRequests();
t.IsWOO = (userControl.FindControl("IsWOO") as CheckBox).Checked;
}
Note the IsWOO is a control in the Radgrid that I did not show in the Screenshot. When I click the save link the Insert Function, shown above Runs but I get the following error:
Unhandled exception at line 1, column 123034 in http://localhost:52028/bundles/MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81
0x800a139e - JavaScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Object reference not set to an instance of an object.
The strange part is I use this same code in several other projects without any problems. The only difference is this is the first time I have used this auto generated form. I don't want to use the another type of control for this Radgrid due to such a small number of fields, only have 4 control.
I have spent several hours searching for an answer but just can't find the solution.
How can I get the values from this auto generated form?

You can use
t.IsWOO = (editedItem["ISWOO"].Controls[0] as CheckBox).Checked;
or
var newValues = new Dictionary<string, object>();
e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
t.IsWOO = (bool)newValues["IsWOO"];
The first approach references the control by index because unfortunately it has no ID.
The second one is a bit verbose for just one property but I would surely prefer it if there were more properties.

While #Michal Nawrocik was correct I found that I still had some problems reading all of the controls in the Radgrid. I was able to track down the answer on the Telerik forum and found that you have to use different code based on the Column Type. I had 2 different type of columns.
the code below shows what I used to get all of the control values on the form
protected void SpecialRequests_InsertCommand(object sender, GridCommandEventArgs e)
{
try
{
using(LatentEntities db = new LatentEntities())
{
if (e.Item is GridEditableItem)
{
T_SpecialRequests T = new T_SpecialRequests();
var editableItem = ((GridEditableItem)e.Item);
RadDatePicker picker = (RadDatePicker)editableItem.FindControl("dpDate"); // in EditItem Template
DateTime dt = Convert.ToDateTime(picker.DbSelectedDate);
T.Date = dt;
TextBox Reason = (TextBox)editableItem.FindControl("txtReason"); //This Control was in an Edit Item Template
T.Reason = Reason.Text;
T.IsWOO = (editableItem["ISWOO"].Controls[0] as CheckBox).Checked; //In CheckBox Column
}
}
And if the control is in a Telerik:GridtboundColumn I used this code:
string strFirstName = (editableItem["firstname"].Controls[0] as TextBox).Text;

Related

Telerik : Get Column name from FilterTemplate controls Client Event

I am trying to add RadCombobox to a telerik:GridTemplateColumn as a FilterTemplate control. I have multiple columns and all have RadCombobox with same filter values.
<telerik:GridTemplateColumn AutoPostBackOnFilter="true" HeaderStyle-Width="90px"
UniqueName="Date1" HeaderText="Date1" DataField="Day1">
<FilterTemplate>
<telerik:RadComboBox ID="RadComboBoxDate1" Height="90px" AppendDataBoundItems="true"
Width="105px" runat="server" OnClientSelectedIndexChanged="Date1IndexChanged">
</telerik:RadComboBox>
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function Date1IndexChanged(sender, args) {
var tableView = $find("<%# TryCast(Container,GridItem).OwnerTableView.ClientID %>");
var selectedValue = sender.get_value();
if (selectedValue) {
if (parseInt(selectedValue) < 0) {
tableView.filter("Date1", selectedValue, "NoFilter");
}
else { tableView.filter("Date1", selectedValue, "EqualTo");
}
}
}
</script>
</telerik:RadScriptBlock>
</FilterTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblday1"></asp:Label>
<asp:HiddenField ID="hdDay1" runat="server" Value='<%# DataBinder.Eval(Container.DataItem,"Day1") %>' Visible="false" />
</ItemTemplate>
</telerik:GridTemplateColumn>
I have 7 such columns and I want to use a single RadCodeBlock to handle the filter. Is there any better way to do this?
Solution given on Telerik website worked for me
http://www.telerik.com/forums/how-to-get-column-name-from-filter-template-control-s-js-event

Telerik rad grid combo box event

I m using telerik rad grid
I have used combo box to display company Type.
If company Type is ABC than Design Firm type should not be displayed
how to write code on combobox in telerik radgrid ![enter image description here][1]
You will need to take two steps to make this work. First, set up an EditForm Template in your RadGrid. Next, you'll need to use related RadComboBoxes (as shown in this example) to achieve your desired functionality.
EditForm Template example code
<telerik:GridTemplateColumn UniqueName="ContactTitle" HeaderText="ContactTitle">
<EditItemTemplate>
<telerik:RadComboBox ID="RadComboBox1" AutoPostBack="true" runat="server" SelectedValue='<%# Bind("CountryID") %>' DataSourceID="SqlDataSource1" DataTextField="CountryID" OnSelectedIndexChanged="RadComboBox1_SelectedIndexChanged">
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn UniqueName="TemplateColumn">
<EditItemTemplate>
<telerik:RadComboBox ID="RadComboBox2" runat="server">
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
Cascading ComboBox example
protected void RadComboBox1_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
{
RadComboBox rdcbx = (RadComboBox)o;
GridEditableItem editedItem = rdcbx.NamingContainer as GridEditableItem;
RadComboBox ddList = editedItem.FindControl("RadComboBox2") as RadComboBox;
// change the data source for ddList here
.....
}
source

How to filter list by multiple criterias without reloading page?

I have product list and I should to filter products by multiple criterias. In one page I have multiple criterias (name, price, create date etc.) in differenet elements: textbox, Dropdownlist etc.
I want to search products without reload page. When I change any criteria, product list updates automatically, without reloading page. Like this: Filter users.
Here is my view:
#model IEnumerable<Product>
<section id="sidebar left">
<div class="form_info">
<label>Category</label>
#Html.DropDownListFor(model => model.CategoryId, ViewBag.CategoryList as IEnumerable<SelectListItem>, "-", new { id = "ProductCategory" })
</div>
<div class="form_info">
<label>Name</label>
#Html.TextBoxFor(model => model.Name, new{ id = "ProductName"})
</div>
...//other properties
</section>
<section id="content" >
#foreach (var item in Model)
{
<a class="productStyle" href="#Url.Action("Details", "Product", new { id=item.Id})">#item.Name</a>
}
</section>
I have FilterProductByCriteria(int CategoryId, int Name, double priceFrom, double PriceTo..etc) action in controller.
I can do this: in onchange() event of every element to send all criteria values to controller and call back result data - filtered product list, but I cannot use returned data in #foreach (var item in Model). Help me in it or advice better ways, please. (Sorry for bad english)
I can do this: in onchange() event of every element to send all
criteria values to controller and call back result data - filtered
product list, but I cannot use returned data in #foreach (var item in
Model)
Why not? Sure you can. As an alternative you could place the filter criteria inputs inside an HTML form and provide a submit button that will send the values to the controller and this controller will return the same view with filtered products model. And then you could optimize this by introducing AJAX. You would place the <section id="content"> contents into a partial view which will contain the filtered results. And then you could use an Ajax.BeginForm instead of a regular Html.BeginForm to send the filter criteria to the controller action. In turn this controller action will perform the filtering and pass the filtered product list to the same partial view (return PartialView()) which will then be used to refresh only results section of your DOM.
For example:
#model IEnumerable<Product>
#using (Ajax.BeginForm("Search", "SomeController", new AjaxOptions { UpdateTargetId = "content" }))
{
<section id="sidebar left">
<div class="form_info">
#Html.LabelFor(model => model.CategoryId)
#Html.DropDownListFor(
model => model.CategoryId,
ViewBag.CategoryList as IEnumerable<SelectListItem>,
"-",
new { id = "ProductCategory" }
)
</div>
<div class="form_info">
#Html.LabelFor(model => model.Name)
#Html.TextBoxFor(model => model.Name, new { id = "ProductName"})
</div>
...//other properties
</section>
<button type="submit">Filter</button>
}
<section id="content">
#Html.Partial("_Products", Model)
</section>
and then your controller action might look like this:
[HttpPost]
public ActionResult Search(SearchCriteriaViewModel model)
{
IEnumerable<Product> filteredProducts = ... you know what to do here
return PartialView("_Products", filteredProducts);
}
Please refer this link for searching inside ASP.Net GridView without refresh the page.
[ASP.NET GridView Searching without refresh whole Page]
http://www.ashishblog.com/search-sort-in-gridview-using-c-net-ajax-and-jquery/
Here is my aspx page having search text box and gridview inside AJAX update panel.
<asp:ScriptManager ID="ScriptManager" runat="server" />
Search: <asp:TextBox ID="txtSearch" runat="server" OnTextChanged="txtSearch_TextChanged" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<div class="GridviewDiv">
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
AllowSorting="true" DataSourceID="dsGridview" Width="540px" PageSize="10" CssClass="yui">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" ItemStyle-Width="40px"
ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<ItemStyle Width="120px" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblFirstname" Text='<%# HighlightText(Eval("FirstName").ToString()) %>' runat="server"
CssClass="TextField" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<ItemStyle Width="120px" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblLastname" Text='<%# HighlightText(Eval("LastName").ToString()) %>' runat="server"
CssClass="TextField" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department"
ItemStyle-Width="130px" />
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location"
ItemStyle-Width="130px" />
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
--> Here is my code behind file add method in page load event.
string SearchString = "";
protected void Page_Load(object sender, EventArgs e)
{
txtSearch.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + txtSearch.ClientID.Replace("_", "$") + "\\',\\'\\')', 0);");
if (!IsPostBack)
{
Gridview1.DataBind();
}
}
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
SearchString = txtSearch.Text;
}
public string HighlightText(string InputTxt)
{
string Search_Str = txtSearch.Text.ToString();
// Setup the regular expression and add the Or operator.
Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
// Highlight keywords by calling the
//delegate each time a keyword is found.
return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
// Set the RegExp to null.
RegExp = null;
}
public string ReplaceKeyWords(Match m)
{
return "<span class=highlight>" + m.Value + "</span>";
}

Only one instance of a ScriptManager can be added

Why do I get this error message: Only one instance of a ScriptManager can be added to the page?
I haven't been using HTML comment to hide an ASP.NET server tag and there is no other ScriptManager in the entire project.
Markup:
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblCount" CssClass="LikeCount" Text='<%#Eval("LikeCount") %>' runat="server"></asp:Label>
<asp:LinkButton ID="lbAddOne" CssClass="LikeAddOne" Text="+1" runat="server" OnClick="lbAddOne_Click" CommandArgument='<%#Eval("ReviewID") %>'></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
Code-behind:
protected void lbAddOne_Click(object sender, EventArgs e)
{
LinkButton _sender = (LinkButton)sender;
string ReviewID = _sender.CommandArgument;
int UserID = ((User)Session["LoggedInUser"]).UserID;
lblCount.Text = (int.Parse(lblCount.Text) + 1).ToString();
CategoryAccess.AddLikeReview(ReviewID, UserID);
}
just add a reference to scriptmanager in the masterpage, then it will be available to any page referencing the master. this will be easier to maintain in the long run rather than adding references to individual pages.

ASP.NET Button Inside Repeater Inside UpdatePanel Won't Fire!

ASP.NET 3.5 SP 1 / Visual Studio 2008 V 9.x RTM
I am trying to get a button inside a repeater inside an updatepanel to fire.
I't won't. I have tried adding a trigger outside the ContentTemplate and inside
the UpdatePanel to no avail:
<Triggers>
<asp:AsyncPostBackTrigger ControlID="BtnAddStatus" EventName="Click" />
</Triggers>
In fact, the AsyncPostBackTrigger's ControlID is always red and tells me "Cannot Resolve Symbol". This seems to be the case no matter where on the page I put the trigger.
I have read posts that have solved this problem by putting the button outside
of the UpdatePanel but then, graphically speaking, the button will not be in the
correct spot. It needs to be DIV with the ID of btnDiv.
So... how do I get the below button to fire?
<asp:Button ID="BtnAddStatus" CssClass="small button Detail" Text="Share" runat="server" />
ASPX code as follows:
<asp:Content ContentPlaceHolderID="ContentCenter" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Always" runat="server">
<ContentTemplate>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<asp:Repeater ID="repFilter" runat="server"
onitemcommand="RepFilterItemCommand">
<HeaderTemplate>
<div class="UIComposer_Box">
<span class="w">
<asp:TextBox class="input" ID="txtStatusUpdate" TextMode="MultiLine" Columns="60"
name="txtStatusUpdate" Style="overflow: hidden; height: 40px; color: rgb(51, 51, 51);"
runat="server"></asp:TextBox>
</span>
<br clear="all">
<div id="btnDiv" style="padding: 10px 5px; height: 30px;" align="left">
<span style="float: left;"> PHP, Codeigniter, JQuery, AJAX Programming +
Tutorials ( <a href="http://www.x.info" target="_blank" style="color: rgb(236, 9, 43);">
www.x.info</a> ) </span>
<asp:Button ID="BtnAddStatus" CssClass="small button Detail" Text="Share" runat="server" />
</div>
</div>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label1" Text='<%# ((Alert)Container.DataItem).Message %>' runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<br class="clear" />
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
AND MY PAGE LOAD CODE:
protected void Page_Load(object sender, EventArgs e)
{
_presenter = new DefaultPresenter();
_presenter.Init(this);
}
AND THE BtnStatusClick Method:
protected void BtnAddStatusClick(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var su = new StatusUpdate
{
CreateDate = DateTime.Now,
AccountId = _userSession.CurrentUser.AccountId,
Status = "" //txtStatusUpdate.Text
};
_statusRepository.SaveStatusUpdate(su);
_alertService.AddStatusUpdateAlert(su);
_presenter = new DefaultPresenter();
_presenter.Init(this);
}
}
Thanks again.
Have you tried setting the click event in the button instead of handling it from the code behind?
<asp:Button OnClick="BtnAddStatusClick" ID="BtnAddStatus" CssClass="small button Detail" Text="Share" runat="server" />

Resources