I am using asp.net C# with telerik.
I have radgrid and a button add new record. I press it and fill up the informations but the problem is when I press insert it says that ParentDist and RankLevel can not be null.
In other words I can get the value that i select from the dropdowns. What I do wrong and how I can fix it?
<telerik:GridTemplateColumn DataField="ParentDist" FilterControlAltText="Filter ParentDist column" HeaderText="ParentDist" SortExpression="ParentDist" UniqueName="ParentDist">
<EditItemTemplate>
<telerik:RadDropDownList ID="ParentDistDropDown" runat="server" DataSourceID="ParentSqlDataSource" DataTextField="Name" DataValueField="IDnumber" DefaultMessage="Select If Exists">
</telerik:RadDropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="ParentDistTextBox" runat="server" Text='<%# Eval("ParentDist") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn DataField="RankLevel" DataType="System.Int32" FilterControlAltText="Filter RankLevel column" HeaderText="RankLevel" SortExpression="RankLevel" UniqueName="RankLevel">
<EditItemTemplate>
<telerik:RadDropDownList ID="RadDropDownList1" runat="server" DataSourceID="RankSqlDataSource" DataTextField="RankDescr" DataValueField="RankID" > </telerik:RadDropDownList> </EditItemTemplate>
<ItemTemplate>
<asp:Label ID="RankLevelTextBox" runat="server" Text='<%# Eval("RankLevel") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
InsertCommand="INSERT INTO edmark_distriblist (ParentDist,RankLevel) VALUES ( #ParentDistDropDown, #RadDropDownList1,)"
>
<InsertParameters>
<asp:Parameter Name="ParentDistDropDown" Type="String" ></asp:Parameter>
<asp:Parameter Name="RadDropDownList1" Type="Int32"></asp:Parameter>
</InsertParameters>
Use the Bind expression (https://msdn.microsoft.com/en-us/library/vstudio/ms178366%28v=vs.100%29.aspx), as shown here: http://demos.telerik.com/aspnet-ajax/grid/examples/data-editing/form-template-update/defaultcs.aspx. Note the SelectedValue property of the dropdown lists.
Or, just use the InsertCommand event, access the controls (http://www.telerik.com/help/aspnet-ajax/grid-accessing-cells-and-rows.html) and use their values to compile the query yourself.
Related
I have the below but the update from gridview doesn't seem to work and throws this error:
Incorrect syntax near 'nvarchar'.
Must declare the scalar variable "#id".
I have added the datakeynames to the gridview and the update parameters to the SqlDataSource but still can't see what's wrong...
Doing a delete works fine.
I have tried reduced the update parameters one by one but still not found the cause
<asp:SqlDataSource ID="sqldsEvents" runat="server"
ConnectionString='<%$ ConnectionStrings:dbIPRadioConnectionString %>'
SelectCommand="SELECT id, eventid, [start time], duration, active, [event desc] FROM tblEvents"
UpdateCommand="UPDATE tblEvents SET [start time] = #starttime WHERE (id = #id)"
InsertCommand="INSERT INTO tblEvents(eventid, [start time], duration, active, [event desc]) VALUES (#eventid, #starttime, #duration, #active, #eventdesc)"
DeleteCommand="DELETE FROM tblEvents WHERE (id = #id)">
<DeleteParameters>
<asp:Parameter Name="id"></asp:Parameter>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="eventid"></asp:Parameter>
<asp:Parameter Name="starttime"></asp:Parameter>
<asp:Parameter Name="duration"></asp:Parameter>
<asp:Parameter Name="active"></asp:Parameter>
<asp:Parameter Name="eventdesc"></asp:Parameter>
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="starttime"></asp:Parameter>
<asp:Parameter Name="id"></asp:Parameter>
</UpdateParameters>
</asp:SqlDataSource>
<div class="col-sm-12 text-center">
<asp:GridView ID="gvEvents" runat="server" DataKeyNames="id"
CssClass="table table-bordered" DataSourceID="sqldsEvents"
BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"
CellPadding="4" AutoGenerateColumns="False"
EmptyDataText="No Events Configured">
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton runat="server" Text="Update" CommandName="Update" CausesValidation="True" ID="LinkButton1"></asp:LinkButton> <asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" CausesValidation="False" ID="LinkButton2"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Edit" CommandName="Edit" CausesValidation="False" ID="LinkButton1"></asp:LinkButton> <asp:LinkButton runat="server" Text="Select" CommandName="Select" CausesValidation="False" ID="LinkButton2"></asp:LinkButton> <asp:LinkButton runat="server" Text="Delete" CommandName="Delete" CausesValidation="False" ID="LinkButton3"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" SortExpression="id"></asp:BoundField>
<asp:BoundField DataField="eventid" HeaderText="eventid" SortExpression="eventid"></asp:BoundField>
<asp:BoundField DataField="start time" HeaderText="start time" SortExpression="start time"></asp:BoundField>
<asp:BoundField DataField="duration" HeaderText="duration" SortExpression="duration"></asp:BoundField>
<asp:BoundField DataField="event desc" HeaderText="event desc" SortExpression="event desc"></asp:BoundField>
<asp:TemplateField HeaderText="active" SortExpression="active">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="0" Value="0"></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("active") %>' ID="Label1"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The problem occurs because DataField attribute inside GridView's BoundField does not accept column names that using whitespaces.
Better to use underscores for DataField and SortExpression field/column names, also using underscore-based alias names for every columns containing whitespaces in SqlDataSource:
GridView control
<asp:GridView ID="gvEvents" ... >
<%-- other fields --%>
<asp:BoundField DataField="start_time" HeaderText="start time" SortExpression="start_time"></asp:BoundField>
<asp:BoundField DataField="event_desc" HeaderText="event desc" SortExpression="event_desc"></asp:BoundField>
<%-- other fields --%>
</asp:GridView>
SqlDataSource control
<asp:SqlDataSource ID="sqldsEvents" runat="server" ConnectionString='<%$
ConnectionStrings:dbIPRadioConnectionString %>'
SelectCommand="SELECT id, eventid, [start time] AS start_time, duration, active, [event desc] AS event_desc FROM tblEvents"
<%-- other items --%>
</asp:SqlDataSource>
Furthermore, if you have access to modify column names in SSMS, changing all column names with whitespaces to underscores like this update command should work without hassle:
UpdateCommand="UPDATE tblEvents SET start_time = #starttime WHERE (id = #id)"
Note:
Column/field names in every table should follow database identifier convention to ensure CRUD commands are executed successfully.
Similar issue: incorrect syntax near nvarchar in gridview
net gridview and I do not wish to use the built in controls and want to bind the data manually in c#. Could some one let me know where to start and how can I use 3 different drop downs to add more filtering?
asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvContactorRowDataBound" Gridlines="Vertical" >
<Columns >
<asp:TemplateField HeaderText="Full Name" SortExpression="contactname" HeaderStyle-BackColor="deepskyblue">
<EditItemTemplate>
<asp:TextBox ID="txtcontactname2" runat="server" Text='<%# Bind("contactname") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorcontactname2" runat="server" ErrorMessage="Full Name is required for contractor update!" Text="*" ForeColor="Red" ControlToValidate="txtcontactname2" display="none"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcontactname2" runat="server" Text='<%# Bind("contactname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="phone" HeaderText="Phone" SortExpression="phone" HeaderStyle-BackColor="deepskyblue"/>
<asp:BoundField DataField="email" HeaderText="Email" SortExpression="email" HeaderStyle-BackColor="deepskyblue"/>
You did not mentioned your scenario, therefore i assume that you want show all of students in grid view and in each row have a Drop down to select teacher. You have another data base Teachers and each teacher has Id and Name. So in your code behind you gathered all of the teachers:
protected List<teacher> teachers;
In each row of Students gridview you must have this column:
<asp:TemplateField HeaderText="Teacher">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="selectClip" DataSource="<%# teachers %>"
DataTextField="Name" DataValueField="Id" AppendDataBoundItems="true">
<asp:ListItem Text="<---Select Teacher--->"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblShowTeacher" runat="server" Text='<%# Bind("Teacher") %>' />
</ItemTemplate>
</asp:TemplateField>
If you want to have your teachers in a SqlDataSource, change this:
DataSource="<%# teachers %> to this: DataSourceId="teachersDataSourceId"
I am trying to utilize a details view and provide the edit feature for a few levels of user authorization. Basically level 1 users cannot update a predefined set of fields but level 2 users can update these fields. I had tried simply setting the field to visible=false when defining the EditTemplate and then in the DataBind I would test for authorization and make it visible=true if the user had privileges to update the field (see code example below). Worked like a charm, except I noticed that when level 1 users update the fields they are allowed to update, the visible=false fields would be set to null (overwritten) in the database. So, been trying various options not to have to duplicate the views etc.
code snippet:
aspx....
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level %>"
SortExpression="LevelId">
<EditItemTemplate>
<asp:DropDownList ID="LevelList" runat="server"
DataTextField="LevelDesc" DataValueField="LevelId">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level1 %>"
SortExpression="Level1Date" Visible="false" >
<EditItemTemplate>
<asp:TextBox ID="Level1" runat="server" Text='<%#
Bind("Level1Date", "{0:d}") %>' />
<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="Please enter a valid date (m/d/y)"
ControlToValidate="Level1" Operator="DataTypeCheck"
Type="Date" Display="Dynamic">
</asp:CompareValidator>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level2 %>"
SortExpression="Level2Date" Visible="false" >
<EditItemTemplate>
<asp:TextBox ID="Level2" runat="server" Text='<%#
Bind("Level2Date", "{0:d}") %>' />
<asp:CompareValidator ID="CompareValidator2" runat="server"
ErrorMessage="Please enter a valid date (m/d/y)"
ControlToValidate="Level2" Operator="DataTypeCheck"
Type="Date" Display="Dynamic">
</asp:CompareValidator>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="<%$ Resources:Resource, Level4 %>"
SortExpression="Level4Date" Visible="false" >
<EditItemTemplate>
<asp:TextBox ID="Level4" runat="server" Text='<%#
Bind("Level4Date", "{0:d}") %>' />
</Fields>
aspx.cs SNIPPET
<name>_DataBound(object sender, EventArgs e)
{
.
.
.
if (User.IsInRole("yyy") || User.IsInRole("xxx))
{
OfficialProfileInfo.Fields[2].Visible = true;
OfficialProfileInfo.Fields[3].Visible = true;
}
You must set the DataKeyNames property for the automatic updating, deleting, and inserting features of the DetailsView control to work.
While updating if some fields should not change, you can put them in the key.
if (User.IsInRole("yyy") || User.IsInRole("xxx))
{
OfficialProfileInfo.Fields[2].Visible = true;
OfficialProfileInfo.Fields[3].Visible = true;
}
else
{
OfficialProfileInfo.DataKeyNames = "Level4Date"
}
Note: DataKeyNames is a comma-seperated list of field names/
I am currently experiencing a really weird problem with deleting a row from a GridView. I have the following code, and it throws the following exception:
ORA-01008: not all variables bound
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="DeleteBTN" runat="server" OnClientClick="return confirm('Are you sure you want to delete this move request?')" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UNIQUEKEY" HeaderText="Unique Key"
SortExpression="UNIQUEKEY" />
<asp:SqlDataSource ID="GridViewDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:Oracle1ConnectionString %>"
ProviderName="<%$ ConnectionStrings:Oracle1ConnectionString.ProviderName %>"
SelectCommand="SELECT ORIGINATOR, TO_CHAR(REQUESTDATE, 'MM/DD/YYYY') as REQUESTDATE, PARTNUMBER, REQUESTQTY, MOVEFROM, MOVETO, COMPLETEDBY, TO_CHAR(COMPLETION_DATE, 'MM/DD/YYYY') as COMPLETION_DATE, COMMENTS, RESPONSETIME, PROCESS_FLAG, UNIQUEKEY FROM MATERIALMOVEREQUEST WHERE RTRIM(PROCESS_FLAG) = :ProcessFlag ORDER BY REQUESTDATE DESC"
DeleteCommand="DELETE FROM MATERIALMOVEREQUEST WHERE UNIQUEKEY = :UNIQUEKEY">
<SelectParameters>
<asp:ControlParameter ControlID="RequestTypeLabel" DefaultValue="" Name="ProcessFlag" PropertyName="Text" Type="String" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="UNIQUEKEY" Type="Decimal" />
</DeleteParameters>
UNIQUEKEY is a 'Number' field in my Oracle table and I have tried all kinds of data types where it is currently a 'decimal' type.
Use Deleting event of SqlDataSource and try writing following code:
e.InputParameters["UNIQUEKEY"] = value;
value is what you want to send to database
Fixed it myself, had to add the primary keys to the GridView parameters (DATAKEYNAMES). Here is my code snippet:
<asp:GridView ID="MMRGrid" runat="server" AutoGenerateColumns="False" DataKeyNames="UNIQUEKEY"
DataSourceID="GridViewDataSource" Width="980px" OnRowDataBound="GridViewRowEventHandler"
EmptyDataText="No Data Found" AllowSorting="True">
<Columns>
<asp:TemplateField HeaderText="Delete" Visible = "true">
<ItemTemplate>
<asp:LinkButton ID="DeleteBTN" runat="server" OnClientClick="return confirm('Are you sure you want to delete this move request?')" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
I have a gridview that receives a data source with 8621 entries with the page size set to 20. The first page is displayed exactly as it should be. I click the link to display page 2, and it also displays as it should. Anything after that however is still page 2. So if I click the link to go to page 3, the paging control updates saying I am on page 3, but the data displayed is the data on page 2. I know the gridview is getting all 8621 entries because if I change the page size to 200 it displays those 200. Why would the gridview work correctly for some pages but not others? Anyways, enough with my rambling, here is the code itself:
<ajax:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<cb:SortedGridView ID="SearchUsersGrid" runat="server" AutoGenerateColumns="False" DataKeyNames="Email"
DefaultSortDirection="Ascending" DefaultSortExpression="Email"
AllowPaging="true" PageSize="20" AllowSorting="true" Width="100%" SkinID="PagedList">
<Columns>
<asp:TemplateField HeaderText="In List">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:CheckBox ID="IsInEmailList2" runat="server" checked='<%#IsInEmailList(Container.DataItem)%>' OnCheckedChanged="IsInEmailList_CheckedChanged" AutoPostBack="true" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email" SortExpression="Email">
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:HyperLink ID="NameLink2" runat="server" Text='<%# Eval("Email") %>' NavigateUrl='<%#GetEditUserUrl(Container.DataItem)%>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="LastName">
<HeaderStyle horizontalalign="Left" />
<ItemStyle horizontalalign="Left" />
<ItemTemplate>
<asp:Label ID="FullNameLabel2" runat="server" Text='<%#GetFullName(Container.DataItem)%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<div align="center">
<asp:Label runat="server" ID="noUsersFound" enableViewState="false" Text="No matching users found."/>
</div>
</EmptyDataTemplate>
</cb:SortedGridView>
</ajax:UpdatePanel>
and some relevant code behind:
SearchUsersGrid.Visible = true;
SearchUsersGrid.DataSourceID = "SearchUsersDs";
SearchUsersGrid.DataBind();
and the data source itself
<asp:ObjectDataSource ID="SearchUsersDs" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="FindUsersByName" TypeName="Builder.Users.UserDataSource"
SelectCountMethod="CountUsersByName" EnablePaging="True" SortParameterName="sortExpression" DataObjectTypeName="Builder.Users.User" DeleteMethod="Delete">
<SelectParameters>
<asp:ControlParameter ControlID="SearchText" Name="searchPattern" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="SearchByDropDown" Name="searchField" PropertyName="SelectedValue" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
There is no PageIndexChanged event. Any ideas?
Remove the AJAX update panel and check if it works as expected.. Another problem might be that if you bind the Grid in page_load make sure it is not posted back everytime.. put it in
if(!IsPostBack)
{
SearchUsersGrid.Visible = true;
SearchUsersGrid.DataSourceID = "SearchUsersDs";
SearchUsersGrid.DataBind();
}
I think the issue had to do with our production server. for some reason the code works great on our production box (even with the same data).