unable to insert Telerik RadGrid In-Place insert using OnInsertCommand e.item - insert

I am trying to perform an insert using teleriks rad grid. I am doing an in-place insert and using the onInsertCommand method to set the values that are to be insertted. i found this statement in telerik's documnetation:
GridEditableItem editedItem = e.Item as GridEditableItem; when i use it editedItem is getting null value and i dont know how to make it work:
Here is my code behind for InsertCommand
protected void RadGrid1_InsertCommand(Object Sender, Telerik.Web.UI.GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
Hashtable newValues = new Hashtable();
e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
editedItem.Edit = false;
Yieldco.RS.Libraries.BusinessObjects.UnitType u1 = new Yieldco.RS.Libraries.BusinessObjects.UnitType();
u1.Description = newValues["Description"].ToString();
u1.UnitTypeID = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["UnitTypeID"]);
u1.CommunityID = 1;
u1.CompanyID = 1;
u1.Bathrooms = (float)Convert.ToDouble(newValues["Bathrooms"]);
u1.Bedrooms = Convert.ToInt32(newValues["Bedrooms"]);
u1.SqFtHigh = (float)Convert.ToDouble(newValues["SqFtHigh"]);
u1.SqFtLow = (float)Convert.ToDouble(newValues["SqFtLow"]);
u1.NumOfUnits = Convert.ToInt32(newValues["NumOfUnits"]);
u1.ProCon = Convert.ToInt32(newValues["ProCon"]);
u1.OthCon = Convert.ToInt32(newValues["OthCon"]);
u1.RentHigh = (float)Convert.ToDouble(newValues["RentHigh"]);
u1.RentLow = (float)Convert.ToDouble(newValues["RentLow"]);
u1.Status = 1;
int id = MSController.SaveUnitTypes(u1);
}
and my aspx radgrid
AutoGenerateColumns="false" AllowAutomaticUpdates="false" AllowAutomaticInserts="false" DataKeyNames="UnitTypeID" GridLines="Both"
EditItemStyle-Width="24px">
<%--
--%>
' runat="server" ID="Addnew" Text="Add New" CommandName="InitInsert" />
' runat="server" ID="CancelAdd" Text="Cancel" CommandName="CancelAll" />
' runat="server" ID="InsertNew" Text="Perform Insert" CommandName="PerformInsert" />
' runat="server" ID="EditAll" Text="Edit All" CommandName="EditAll" />
0 %>' runat="server" ID="CancelEdit" Text="Cancel" CommandName="CancelAll" />
0 %>' runat="server" ID="UpdateAll" Text="Update All" CommandName="UpdateAll" OnClientClick='javascript:return confirm("Are you sure you want to Update All Records?")' />
<asp:ObjectDataSource ID="odsGetUnitTypes" runat="server"
TypeName="Yieldco.RS.Libraries.Controllers.MSController"
DataObjectTypeName="Yieldco.RS.Libraries.BusinessObjects.UnitType"
SelectMethod="GetUnitTypesByCommunityID"
InsertMethod="SaveUnitTypes"
UpdateMethod="SaveUnitTypes"
>
<SelectParameters>
<asp:Parameter DefaultValue="1" Name="CommunityID" />
</SelectParameters>
</asp:ObjectDataSource>
Please help me out to make a sucessful insertion.
Also in the Telerik documentation I saw them using e.ite.item index for getting the vdatakeyvalue but if I use it the index is always showing up as -1 so I used editedItem.ItemIndex and it works fine
Thanks in advance

To reference the insert item, you should use the following syntax (as opposed to edited item):
if(e.CommandName = RadGrid.PerformInsertCommandName)
{
GridEditableItem editItem = e.Item.OwnerTableView.GetInsertItem();
}

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 RadGrid EditTemplateColumn no value in textbox

I have a RadGrid and two columns. One Databound holding existing password and one EditTemplateColumn with a password confirmation textbox.
Since I want compare/validate the passwords I need to find the controls and the values.
The problem is that I can find the controls in the Radgrid ItemDataBound event, but not the inputed value for the confirm password textbox.
<telerik:GridBoundColumn DataField="Password" HeaderText="Password" UniqueName="Password" HeaderStyle-Width="130px" >
<ColumnValidationSettings EnableRequiredFieldValidation="true" EnableModelErrorMessageValidation="true">
<RequiredFieldValidator ForeColor="Red" ErrorMessage="Password is missing"></RequiredFieldValidator>
<ModelErrorMessage BackColor="Red" />
</ColumnValidationSettings>
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="PasswordConfirm" HeaderText="Confirm password" Display ="false" >
<EditItemTemplate>
<Telerik:RadTextBox ID="textBoxPasswordConfirm" Runat="server" >
</Telerik:RadTextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="textBoxPasswordConfirm"
ForeColor="Red" ErrorMessage="Password missing" >
</asp:RequiredFieldValidator>
</EditItemTemplate>
</telerik:GridTemplateColumn>
Here is the corresponding code:
GridEditableItem item = e.Item as GridEditableItem;
TextBox pwd1 = (TextBox)item["Password"].Controls[0];
RadTextBox pwdconfirm = (RadTextBox)item["PasswordConfirm"].FindControl("textBoxPasswordConfirm");
string t1 = pwd1.Text;
// the next line gives an empty string, and I do not understand why ????
string t2 = pwdconfirm.Text;
TableCell cell = (TableCell)pwd1.Parent;
CompareValidator val = new CompareValidator();
val.ControlToValidate = pwd1.ID;
val.ControlToCompare = pwdconfirm.ID;
val.Operator = ValidationCompareOperator.NotEqual;
val.ErrorMessage = "Passwords do not match";
val.ForeColor = Color.Red;
cell.Controls.Add(val);

Delete multiple row with radgrid

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
}
}

Using LinqDataSource with linq to sharepoint for paging

I am developing a a Sharepoint 2010 visual webpart and I am trying to use LinqDataSource in it to handle paging and sorting in a GridView.
I made my datacontext and entity objects with spmetal. and now this is my code:
my mark up:
<%# Register TagPrefix="asp" Namespace="System.Web.UI.WebControls" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<asp:LinqDataSource runat="server" ID="LinqDataSource1" OnSelecting="MySelecting" />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="3"
AutoGenerateColumns="False" DataSourceID="LinqDataSource1"
EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" />
</Columns>
</asp:GridView>
and my code:
protected void MySelecting(object sender, LinqDataSourceSelectEventArgs e)
{
TestEntitiesDataContext dc = new TestEntitiesDataContext("http://sp/sites/test");
e.Result = from item in dc.TestList
select new
{
title = item.Title,
numberField = item.NumberField.ToString()
};
}
Now the problem is when I try to view the webpart on the site I get this error:
Expression of type 'System.Int32' cannot be used for return type 'System.Object'
When I deactivate paging on grid view this error disappears.
Do you have any idea why this is happening?
I 'd be grateful of any help.
for me the following work around has helped:
LinqDataSource1.AutoPage = false;
LinqDataSource1.AutoSort = false;
in MySelecting:
e.Result = [your nice LINQ expression].Skip(e.Arguments.StartRowIndex).Take(e.Arguments.MaximumRows);
e.Arguments.TotalRowCount = [your nice LINQ expression].Count();
And if you need sorting, you should also process e.Arguments.SortExpression.

Resources