LinqDataSource does not support the Select property when the Delete - c#

I have LinqDataSource that being attached to GridView In Asp.net web application.
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="DataClassesDataContext" OnInit="LinqDataSource1_Init"
EnableDelete="True"
EntityTypeName="Id" TableName="CompanysCourses"
OnDeleting="Course_Deleting" OnDeleted="Course_Deleted">
</asp:LinqDataSource>
Within OnInit event I have modified the select and where properties like that
this.LinqDataSource1.Where = "CompanyId == " + UserManager.CompanyId;
this.LinqDataSource1.Select= "Course";
I am selecting table named CompanysCourses and after that filter the result and select specific courses based on company's ID
And this is my grid view
<asp:GridView ID="grdVwCourses" runat="server"
AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="Id" DataSourceID="LinqDataSource1"
OnSelectedIndexChanged="grdVwCourses_SelectedIndexChanged"
CssClass="table table-responsive"
PageSize="10" GridLines="Horizontal"
meta:resourcekey="GridView1Resource1">
<EmptyDataTemplate>
<asp:Label runat="server" ID="NotFoundLabel" Text="" meta:resourcekey="NotFoundLabelResource1"></asp:Label>
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="#" meta:resourcekey="HeaderId">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" Visible="false"/>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" meta:resourcekey="BoundFieldResource1" />
<asp:BoundField DataField="EnglishName" HeaderText="EnglishName" SortExpression="EnglishName" meta:resourcekey="BoundFieldResource2" />
<asp:BoundField DataField="CreatedDate" HeaderText="CreatedDate" SortExpression="CreatedDate" meta:resourcekey="BoundFieldResource3" />
<asp:TemplateField meta:resourcekey="TemplateFieldResource1">
<ItemTemplate>
<asp:HyperLink ID="userLink" runat="server" NavigateUrl='<%# GetCategoriesLink(Eval("Id")) %>' Text="Categories" meta:resourcekey="userLinkResource1" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" ShowDeleteButton="True" meta:resourcekey="CommandFieldResource1" />
</Columns>
</asp:GridView>
I have in the grid view enabled deleting but when click delete I got this exception
LinqDataSource 'LinqDataSource1' does not support the Select property
when the Delete, Insert or Update operations are enabled.
I have override On_Deleting event like that to show confirmation dialog
protected void Course_Deleting(object sender, LinqDataSourceDeleteEventArgs e)
{
e.Cancel = true
this.panMessage.Visible = true;
int id = ((Course)e.OriginalObject).Id;
ViewState["DeleteObject"] = id;
}
I wonder what is the reason of this problem.
Edit
The question referred to as duplicate to mine doesn't have the answer that I seek, also the details are different.

I came today to the same issue on some legacy project, as the error showing this widget doesn't support deleting when you use SELECT statement.
so the solution is to remove your select statement from this datasource, ie remove this line:
this.LinqDataSource1.Select= "Course";
then on the gridview change DataKeyNames to your table Id name and also change the navigation property to access the fields, for example Course.Id, Course.Name etc for each columns in the fields.
the last thing is to cast to the main table and use the any field to access the Id of that table child value.
int id = ((Course)e.OriginalObject).Id;

Related

how to make hyperlink in gridview without datafield?

Developing In: c# asp.net web forms 4.5
I've looked at many posts and all of them made a hyperlink with either datafield in it, by datatextfield() or similar.. or called eval from backend.
I didn't do neither of that, so I tried doing every thing I could but it didn't work. CommandField, HyperLinkeField, HyperLink, .. all didn't work.
The main point is that the data comes out fine, but I can't seem to make it hyperlink. Is it impossible to have a hyperlink this way?
I'm trying to make a hyperlink on gridview.
The thing is that the column I'm trying to make the hyperlink
doesn't get data from the datafield.
It gets it by onRowDataBound method of gridview
something like this..
<asp:GridView runat="server" ID="someGrid" CellPadding="10"
DataKeyNames="idx" AutoGenerateColumns="false"
selectMethod="someGrid_GetData" ItemType="someTable"
updateMethod="someGrid_UpdateItem" AutoGenerateEditButton="true"
deleteMethod="someGrid_DeleteItem" AutoGenerateDeleteButton="true"
onRowDataBound="someGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="thing1" HeaderText="thing1" />
<asp:BoundField DataField="thing2" HeaderText="thing2"/>
<asp:DynamicField DataField="poDate" DataFormatString="{0:d}" />
<asp:BoundField HeaderText="vendor" />
<asp:CommandField HeaderText="sku" ShowSelectButton="true" SelectText="{0}" ButtonType="Link"/>
</Columns>
</asp:GridView>
and on the code background, it goes like this..
protected void soGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
using (soAction soa = new soAction())
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string s = e.Row.Cells[2].Text;
string thin1 = soa.get_thin1(s);
e.Row.Cells[4].Text = thin1;
string thin2 = soa.get_thin2(s);
e.Row.Cells[5].Text = thin2;
}
}
}
Thanks!
edit :
Maybe I wasn't clear about what is the challenge here..
normally the examples use dataTextField property in gridview but
I cannot use the dataTextField property because I'm binding the data
depending on the model rendered afterwards.
I'm doing this because I wanted to set the itemType into someTable
so I can use the updatemethod and deleteMethod of the asp.net.
Just use a TemplateField like this, you can do anything you want in a templatefield, combine data from multiple columns, create controls, whatever:
<Columns>
<asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("FirstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/data-access/custom-formatting/using-templatefields-in-the-gridview-control-cs

ASP.NET SqlDataSource filter behaviour

I have a GridView object fed trough a SqlDataSource. In the same form I have also a number of TextBoxes used to build a filtering expression for the datasource. The filtering is started by pressing a Button.
<asp:GridView
DataSourceID="sdsTable1"
OnSorting="gvTable1_Sorting"
OnPageIndexChanging="gvTable1_PageIndexChanging"
runat="server"
CssClass="list_table"
ID="_gvTable1"
CellPadding="0" CellSpacing="0"
AutoGenerateColumns="false"
EmptyDataText="No data."
ShowHeader="true" ShowFooter="true"
AllowSorting="true"
AllowPaging="true"
PageSize="10"
OnRowDataBound="gvTable1_RowDataBound" >
<HeaderStyle CssClass="header" />
<FooterStyle CssClass="footer" />
<PagerSettings
Visible="true"
Mode="NumericFirstLast"
PageButtonCount="3"
Position="Bottom"
NextPageText="Next page"
PreviousPageText="Prev page"
FirstPageText="First page"
LastPageText="Last page" />
<RowStyle CssClass="odd" />
<AlternatingRowStyle CssClass="even" />
<PagerStyle HorizontalAlign="Center" />
<Columns>
<asp:TemplateField Visible="false">
<HeaderTemplate> </HeaderTemplate>
<ItemTemplate>
<%#Eval("id")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date" SortExpression="date">
<ItemTemplate>
<%#Eval("date","{0:dd/MM/yyyy HH:mm:ss}")%>
</ItemTemplate>
<FooterTemplate>
TOTALE:
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Bind("price","{0:F2} €") %>'>></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="0"></asp:Label
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="description" HeaderText="Description" SortExpression="description" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsTable1" runat="server"
ConnectionString="<%$ ConnectionStrings:_db %>"
ProviderName="<%$ ConnectionStrings:_db.ProviderName %>"
DataSourceMode="DataSet"
SelectCommand=" SELECT id, id_user, price, description FROM view1 WHERE id_user = #id_user;">
<SelectParameters>
<asp:SessionParameter Type="Int32" Name="id_user" SessionField="USER_ID" />
</SelectParameters>
</asp:SqlDataSource>
In codebehind (in the event hanlder associated with the Button mentioned above) I build up the filter expression chaining TextBoxes values, with this code:
if (!string.IsNullOrWhiteSpace(_txtFilter0.Text.Trim()))
{
_sFilter += "(description LIKE '%" + _txtFilter0.Text.Trim() + "%')";
}
if (!string.IsNullOrWhiteSpace(_txtFilter1.Text.Trim()))
{
if (!string.IsNullOrWhiteSpace(_sFilter))
_sFilter += " AND";
_sFilter += "(description LIKE '%" + _txtFilter1.Text.Trim() + "%')";
}
sdsTable1.FilterExpression = _sFilter;
Everything works until I clear the fields that leads to an empty filter, im such circumstances I expected to retrieve all the records but for some reason, in this case, the last recordset is kept and shown apparently without a reason.
I tried also to disable the SQLDataSource caching feature without luck:
EnableCaching="false"
I tried also to issue a Select command, again without luck:
sdsTable1.Select(DataSourceSelectArguments.Empty);
Where I'm wrong?
Your _sFilter property will be persisted across postbacks, so as you're only updating it when your filter text boxes are not empty it will remain at the last set value when you clear them. Putting a breakpoint in your code at the line _sdsTable1.FilterExpression = _sFilter; should confirm this.
To solve the issue, either clear the _sFilter property before rebuilding it in your event handler, or write an additional check:
if (string.IsNullOrWhiteSpace(_txtFilter1.Text.Trim()) & string.IsNullOrWhiteSpace(_txtFilter0.Text.Trim()) )
{
_sFilter = null;
}

GridView adding column with button

I need to add column with button in GridView ? i tied with asp:button i got error also i tried asp:ButtonField i got this error:
"Error Creating Control - narudzbaGridType 'System.Web.UI.WebControls.ButtonField' does not have a public property named 'ID'.
but i gave ID name to my Button field asp:ButtonField ID="example"
<asp:GridView ID="narudzbaGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Let" HeaderText="Let"/>
<%--<asp:BoundField DataField="Kolicina" HeaderText="Kolicina"/>--%>
</Columns>
</asp:GridView>
You can use TemplateField like this (add to columns block):
<asp:templatefield headertext="Author Name">
<itemtemplate>
<asp:button id="buttonl"
Text= 'Click Me'
runat="server"/>
</itemtemplate>
</asp:templatefield>
Hi you need to add an TemplateField. Everybody like use ImageButton but if you want use other control go ahead.
<asp:TemplateField HeaderText="Edit" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:ImageButton ID="imgBtnEditar" runat="server" ImageUrl="~/iconos/Image.png" CommandName="edit" ToolTip="Edit">
</asp:ImageButton>
</ItemTemplate>
<ItemStyle Height="8px"></ItemStyle>
</asp:TemplateField>

How do I Pass Multiple Selected Datagrid Values to Another Page in asp.net?

I have multiple asp.net data grids that a user can select a checkbox to the corresponding value that they want, put in the amount they want in a textbox and submit the request. How do I show what values they requested with the amount on the next page? I can do this with a session I believe but I'm having a hard time finding good examples for something like this. Since they can select multiple values I can't use a query string right? I'm using VB.net but if you answer in c# that's fine. Thanks!
<asp:GridView ID="flexGridView" DataKeyNames="ID" runat="server" AutoGenerateColumns="False" DataSourceID="FormSqlDataSource" CssClass="gridView" ClientIDMode="Static">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="flexCheckBoxList" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Form" ShowHeader="False" />
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" Visible="False" />
<asp:BoundField DataField="Category" HeaderText="Category" SortExpression="Category" ShowHeader="False" Visible="False" />
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%# Eval("Email")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qty" >
<ItemTemplate>
<asp:TextBox ID="flexTextBox" runat="server" Width="40" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can use Session or query string, but I would recommend Session, as there are limitations on the length of a query string, especially if you are not sure how many check boxes might be checked.
Use the OnCheckChanged event of the check box control and set AutoPostBack to true in your template field, like this:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="flexCheckBoxList" runat="server"
AutoPostBack="True" OnCheckedChanged="Check_Clicked" />
</ItemTemplate>
</asp:TemplateField>
protected void Check_Clicked(Object sender, EventArgs e)
{
// Store the check box name, ID or whatever unique value you want in Session here
CheckBox theCheckBox = sender as CheckBox;
// Was the check box found?
if(theCheckBox != null)
{
// Store in Session
Session["CheckBoxValue"] = theCheckBox.SomePropertyValue;
}
}
Then in the Page_Load of your redirect page, you will need to read out the Session value for the checked check boxes.

How to define number of rows of GridView at runtime in code behind using C#

I need to develop such a program in which the GridView's rows should be decided at run time.
i.e. I have a table in database called dealer capacity.
Dealer_ID Capacity
D0001 5
Now when the Dealer D00001 is selected from combo box the number of rows in grid view should be 5. I want to use the template field also.
My code for GridView is:
<asp:GridView ID="grdlicence" runat="server" DataKeyNames="Version_id" GridLines="None" BorderStyle="Solid" AutoGenerateColumns="false" AllowSorting="true"
CssClass="mGrid table"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" >
<Columns>
<asp:BoundField DataField="Version_name" ItemStyle-CssClass="uppercase" ItemStyle-Width="150px" HeaderText="Version" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Version_id" Visible="false" HeaderText="Version" HeaderStyle-HorizontalAlign="Left" />
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<center><asp:TextBox ID="txtprice" CssClass="alignments TextStyle" MaxLength="5" runat="server" ></asp:TextBox></center>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Licence Id">
<ItemTemplate>
<center><asp:TextBox ID="txtlicenceid" CssClass="alignments uppercase" runat="server" ></asp:TextBox></center>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Purchase Date">
<ItemTemplate>
<center><asp:TextBox ID="txtpurchasedate" onfocus="showCalendarControl(this);" CssClass="alignments TextStyle" runat="server"></asp:TextBox></center>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiry Date">
<ItemTemplate>
<center><asp:TextBox ID="txtexpirydate" onfocus="showCalendarControl(this);" CssClass="alignments TextStyle" runat="server"></asp:TextBox></center>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Upload File">
<ItemTemplate>
<center><asp:FileUpload ID="fileUpload" runat="server" /></center>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to define PageSize for your GridView and remember to set AllowPaging to true for the GridView
GridView.PageSize Property
Gets or sets the number of records to display on a page in a GridView
control.
The default is 10.
You may see this article: GridView Paging Sample in ASP.NET
You can use the linq Take() and pass the number as parameter.
Updated according to the comment, use following code.
grdlicence.DataSourse= ds.Take(5);
grdlicence.DataBind();

Categories