Parameter for deleting a row - c#

I have a problem with my delete parameter. I am using a GridView and a ObjectDataSource.
And I would like to delete one row. But when I debug is see that the value of CustomerId is always 0 in my Business Logic Layer.
Here is my code
I have two delete parameters, Id and CustomerId. These are the same names as the ones in my BLL.
<asp:GridView DataKeyNames="Id" ID="gvFavoriteMovies" DataSourceID="odsFavoriteMovies" AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTitel" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Title")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="odsFavoriteFilm" runat="server"
TypeName="MovieMonstrDataLayer.bll.BLLMovies"
SelectMethod="GetFavoriteMoviesFromUser"
DeleteMethod="DeleteFavoriteMoviesFromUser"
onobjectcreating="odsFavoriteFilm_ObjectCreating"
ondeleting="odsFavoriteFilm_Deleting">
<DeleteParameters>
<asp:Parameter Name="Id" DbType="Int32" Direction="Input" />
<asp:Parameter Name="CustomerId" DbType="Int32" Direction="Input" />
</DeleteParameters>
<SelectParameters>
<asp:Parameter DbType="Int32" Direction="Input" Name="CustomerId" />
</SelectParameters>
</asp:ObjectDataSource>
This is in the the code behind file
When deleting a row, I assign the value of the logged in Customer to the Delete Parameter CustomerId. This all works. I give the right value to the delete parameter.
protected void odsFavoriteFilm_Deleting(object sender, ObjectDataSourceMethodEventArgs e)
{
if (Context.User.Identity.IsAuthenticated)
{
this.odsFavoriteFilm.DeleteParameters["CustomerId"].DefaultValue = ((MovieMonstrIdentity)Context.User.Identity).Customer.Id.ToString();
this.odsFavoriteFilm.DataBind();
}
}
Normally in my Business Logic Layer, I should get now the right CustomerId, but I always get 0. While no Costumer has that ID.
public int DeleteFavoriteFilmFromUser(int Id, int CustomerId)
{
try
{
return Adapter.DeleteFavoriteFilmFromUser(Id, CustomerId);
}
catch (Exception ex)
{
throw ex;
}
}
What am I doing wrong?

Include CustomerID in your DataKeyNames
<asp:GridView DataKeyNames="Id,CustomerId" ...>
Either do this before the updating
protected odsFavoriteFilm_DataBinding(object sender, EventArgs e) {
if(!IsPostBack) {
this.odsFavoriteFilm.DeleteParameters["CustomerId"].DefaultValue = ((MovieMonstrIdentity)Context.User.Identity).Customer.Id.ToString();
}
}
or set the actual parameter value for the command
protected void odsFavoriteFilm_Deleting(object sender, ObjectDataSourceMethodEventArgs e) {
if (Context.User.Identity.IsAuthenticated) {
e.Command.Parameters["CustomerId"].Value = ((MovieMonstrIdentity)Context.User.Identity).Customer.Id.ToString();
}
}

Related

gridview control not refreshing?

I have what I hope is a simple question. I have a gridview control that's bound to a sqldatasource.
First, the relevant code:
<asp:DropDownList ID="cboCustomerID" runat="server"
DataSourceID="DataSourceCustomer" DataTextField="CustomerName" DataValueField="CustomerID">
</asp:DropDownList>
<asp:DropDownList ID="cboStaffID" runat="server"
DataSourceID="DataSourceStaff" DataTextField="StaffFullName" DataValueField="StaffID">
</asp:DropDownList>
<div><gcctl:MyCheckBox ID="chkShowClosed" Text="Show Closed Jobs?" Checked="false" AutoPostBack="true" runat="server" /></div>
<div><asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" Text="Search" /></div>
<div id="customersearchresults" class="searchresults">
<asp:SqlDataSource id="gvJobsDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:GeekCommandConnString %>"
SelectCommand="SELECT j.JobID, j.JobName, s.JobStatus, jal.[JobAssignmentsFullList]
FROM (SELECT * FROM [dbo].[Jobs] WHERE ((NULLIF(#CustomerSearch,'') IS NOT NULL AND CustomerID = #CustomerSearch) OR (NULLIF(#CustomerSearch,'') IS NULL))) j
INNER JOIN (SELECT * FROM [list].[JobStatuses] WHERE ((#ShowClosed = 0 AND IsStatusOpen = 1) OR (#ShowClosed = 1)) AND IsActive = 1) s ON j.JobStatusID = s.JobStatusID
LEFT JOIN (SELECT * FROM [dbo].[JobAssignments] WHERE ((NULLIF(#StaffSearch,'') IS NOT NULL AND StaffID = #StaffSearch) OR (NULLIF(#StaffSearch,'') IS NULL))) ja ON j.JobID = ja.JobID
LEFT JOIN [dbo].[udv_JobAssignmentsCommaDelimited] jal ON j.JobID = jal.JobID
">
<SelectParameters>
<asp:Parameter Name="CustomerSearch" Type="Int32" />
<asp:Parameter Name="StaffSearch" Type="Int32" />
<asp:Parameter Name="ShowClosed" Type="Boolean" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="gvJobs" runat="server" AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="JobID"
DataSourceID="gvJobsDataSource"
AutoGenerateDeleteButton="False"
AutoGenerateEditButton="False"
AutoGenerateSelectButton="False"
CssClass="searchresultsgrid"
AllowPaging="True" PageSize="50"
OnRowCommand="gvJobs_RowCommand"
EmptyDataText="No matching jobs on record." >
<Columns>
<asp:templatefield>
<itemtemplate>
<asp:linkbutton id="btnEdit" runat="server" CommandName="JobEdit" OnClientClick="PageForm.target ='_blank';" text="View/Edit" />
</itemtemplate>
</asp:templatefield>
<asp:BoundField DataField="JobID" HeaderText="ID" InsertVisible="false" ReadOnly="true" Visible="false" SortExpression="JobID" />
<asp:templateField HeaderText="Job Name" SortExpression="JobName">
<ItemTemplate><%# Eval("JobName") %></ItemTemplate>
</asp:templateField>
<asp:templateField HeaderText="Assigned to" SortExpression="JobAssignmentsFullList">
<ItemTemplate><%# Eval("JobAssignmentsFullList") %></ItemTemplate>
</asp:templateField>
</Columns>
</asp:GridView>
</div>
<asp:SqlDataSource ID="DataSourceCustomer" runat="server"
ConnectionString="<%$ ConnectionStrings:GeekCommandConnString %>"
SelectCommand="SELECT NULL AS [CustomerID]
, NULL AS [CustomerName]
UNION SELECT [CustomerID]
,[CustomerName]
FROM [GeekCommand].[dbo].[Customers]
WHERE ((#ShowInactive = 0 AND IsActive = 1) OR (#ShowInactive = 1))
ORDER BY CustomerName">
<SelectParameters>
<asp:ControlParameter Name="ShowInactive" Type="Boolean" ControlID="chkCustomersShowInactive" PropertyName="Checked" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="DataSourceStaff" runat="server"
ConnectionString="<%$ ConnectionStrings:GeekCommandConnString %>"
SelectCommand="SELECT NULL AS [StaffID]
, NULL AS [StaffFullName]
UNION SELECT [StaffID]
,COALESCE([FirstName], [Nickname], '') + ' ' + COALESCE([LastName], '') AS StaffFullName
FROM [GeekCommand].[dbo].[Staff]
WHERE ((#ShowInactive = 0 AND IsActive = 1) OR (#ShowInactive = 1))
ORDER BY StaffFullName">
<SelectParameters>
<asp:ControlParameter Name="ShowInactive" Type="Boolean" ControlID="chkStaffShowInactive" PropertyName="Checked" />
</SelectParameters>
</asp:SqlDataSource>
And the relevant aspx.cs code:
int? iCustomerID;
int? iStaffID;
//--------
protected void SetIDs()
{
this.iCustomerID = null;
this.iStaffID = null;
if (Request.QueryString["customerid"] != null) //new customer
{
try
{
this.iCustomerID = Convert.ToInt32(Request.QueryString["customerid"]);
}
catch { }
}
if (Request.QueryString["staffid"] != null) //new customer
{
try
{
this.iStaffID = Convert.ToInt32(Request.QueryString["staffid"]);
}
catch { }
}
if (iCustomerID != null)
{
cboCustomerID.SelectedValue = iCustomerID.ToString();
}
if (iStaffID != null)
{
cboStaffID.SelectedValue = iStaffID.ToString();
}
}
//--------
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetIDs();
}
}
//--------
protected void btnSearch_Click(object sender, EventArgs e)
{
gvJobsDataSource.SelectParameters["CustomerSearch"].DefaultValue = cboCustomerID.SelectedValue.ToString();
gvJobsDataSource.SelectParameters["StaffSearch"].DefaultValue = cboStaffID.SelectedValue.ToString();
gvJobsDataSource.SelectParameters["ShowClosed"].DefaultValue = chkShowClosed.Checked.ToString();
gvJobs.DataBind();
}
When I run the following in SSMS, I get 2 rows back, as I should:
DECLARE #CustomerSearch int, #StaffSearch int, #ShowClosed bit
SELECT #CustomerSearch = 2331, #StaffSearch = '', #ShowClosed = CAST(0 AS bit)
SELECT j.JobID, j.JobName, s.JobStatus, jal.[JobAssignmentsFullList]
FROM (SELECT * FROM [dbo].[Jobs] WHERE ((NULLIF(#CustomerSearch,'') IS NOT NULL AND CustomerID = #CustomerSearch) OR (NULLIF(#CustomerSearch,'') IS NULL))) j
INNER JOIN (SELECT * FROM [list].[JobStatuses] WHERE ((#ShowClosed = 0 AND IsStatusOpen = 1) OR (#ShowClosed = 1)) AND IsActive = 1) s ON j.JobStatusID = s.JobStatusID
LEFT JOIN (SELECT * FROM [dbo].[JobAssignments] WHERE ((NULLIF(#StaffSearch,'') IS NOT NULL AND StaffID = #StaffSearch) OR (NULLIF(#StaffSearch,'') IS NULL))) ja ON j.JobID = ja.JobID
LEFT JOIN [dbo].[udv_JobAssignmentsCommaDelimited] jal ON j.JobID = jal.JobID
But when I select a customer (specifically the customer whose id is 2331) in debug mode and step through the btnSearch_Click code, cboCustomerID.SelectedValue = "2331", cboStaffID.SelectedValue = "", chkShowClosed.Checked = false (all of which is correct)... but nothing happens when I step past the databind command. The gridview continues to show "No matching jobs on record."
I feel like I'm missing something really obvious, but I can't for the life of me figure out what it is.
UPDATE: Ok. This is interesting. Apparently, the query never gets sent to the SQL Server. I just started up SQL Server in trace mode, reloaded the aspx page, and did a search, and while the queries that are behind the two dropdownlists are there in the log, the query that's behind the gridview is just not there.
UPDATE #2: I've replaced the select parameters with the following:
<asp:ControlParameter Name="CustomerSearch" ControlID="cboCustomerID" PropertyName ="SelectedValue" />
<asp:ControlParameter Name="StaffSearch" ControlID="cboStaffID" PropertyName ="SelectedValue" />
<asp:ControlParameter Name="ShowClosed" Type="Boolean" ControlID="chkShowClosed" PropertyName="Checked" />
...and removed the extra code in the btnSearch_Click event, so the only line in that code is:
protected void btnSearch_Click(object sender, EventArgs e)
{
gvJobs.DataBind();
}
...no change. Still nothing happens when I click the search button.
Yay! Found the answer:
https://forums.asp.net/t/1243253.aspx?Gridview+Databind+Not+Working
The issue was that the gridviews have a property: CancelSelectOnNullParameter, which is true by default. Since at least one of the drop down lists is almost always null when I do the search, this resulted in nothing happening when I hit the search button. When I added CancelSelectOnNullParameter="false" to the gridview control, it fixed the problem.
(Semi-related note) I also added the following to the ControlParameters: ConvertEmptyStringToNull="true"

SQLDataStore with output parameters, getting ParameterName not contained in this SqlParameterCollection error

The ultimate goal of what I am trying to accomplish is this:
Button at the bottom of a material order form Inserts a new record in the material order table with the ProjectID and current date. After the record is inserted, redirect the page to the new order id so it can be modified.
If I take out the OnInserted method that is supposed to grab the SCOPE_IDENTITY() output of the insert, the record inserts fine, but with the call, I keep getting "SQLParameter with ParameterName 'NewOrderID' is not contained by this SqlParameterCollection"
ASPX Formview
<asp:FormView ID="FvFooter" runat="server" DataKeyNames="OrderID"
DataSourceID="FvMatOrdersSQL" ForeColor="#333333" OnItemCommand="FvFooter_OnItemCommand">
<ItemTemplate>
<br/>
<b>Notes</b>
<br/>
<asp:Label ID="TxtNotes" runat="server" BorderStyle="Solid" BorderWidth="1"
Text='<%# Eval("Notes").ToString().Replace(Environment.NewLine, "<br />") %>'/>
<br/>
<asp:LinkButton ID="LbEditNotes" runat="server" CssClass="NoPrint"
CausesValidation="False" CommandName="Edit" Text="Edit"/>
<br/>
<br/>
<asp:Button ID="DeleteButton" runat="server" CausesValidation="False"
CssClass="NoPrint" CommandName="DeleteOrder" Text="Delete"/>
<asp:Button ID="NewButton" runat="server" CausesValidation="True"
CssClass="NoPrint" CommandName="NewOrder" Text="New Order"/>
<asp:Button ID="EmailButton" runat="server" CausesValidation="True"
CssClass="NoPrint" CommandName="Email" Text="Email"/>
</ItemTemplate>
</asp:FormView>
SQL DataSource
<asp:SqlDataSource ID="FvMatOrdersSQL" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectLogicTestConnectionString %>"
SelectCommand="SELECT mo.OrderID, mo.ProjectID, p.ProjectName, mo.OrderedByEmpID, emp.Name,
mo.OrderDate, mo.DateNeeded, mo.ReasonID, mor.Description, mo.Notes
FROM tblMatOrder AS mo
LEFT OUTER JOIN tblMatOrderReason AS mor ON mo.ReasonID = mor.ReasonID
INNER JOIN tblProject AS p ON mo.ProjectID = p.ProjectID
LEFT OUTER JOIN tblEmployee AS emp ON mo.OrderedByEmpID = emp.EmployeeID
WHERE mo.OrderID = #OrderID"
DeleteCommand="DELETE FROM tblMatOrder WHERE OrderID = #OrderID"
InsertCommand="INSERT INTO tblMatOrder (OrderDate, ProjectID) VALUES (#OrderDate, #ProjectID);
SELECT #NewOrderID = SCOPE_IDENTITY()"
UpdateCommand="UPDATE tblMatOrder SET OrderDate = #OrderDate, OrderedByEmpID = #OrderedByEmpID,
DateNeeded = #DateNeeded, ReasonID = #ReasonID, Notes = #Notes
WHERE OrderID = #OrderID"
OnInserted="FvMatOrdersSQL_OnInserted">
<SelectParameters>
<asp:RouteParameter Name="OrderID" Type="Int32" RouteKey="OrderID"/>
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="OrderID" Type="Int32" DefaultValue="0"/>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="OrderDate" Type="DateTime"/>
<asp:Parameter Name="ProjectID" Type="Int32"/>
<asp:Parameter Direction ="Output" Name="NewOrderID" Type="Int32" DefaultValue="0"/>
</InsertParameters>
<UpdateParameters>
<asp:RouteParameter Name="OrderID" Type="Int32" RouteKey="OrderID"/>
<asp:Parameter Name="OrderDate" Type="DateTime"/>
<asp:Parameter Name="OrderedByEmpID" Type="Int32"/>
<asp:Parameter Name="DateNeeded" Type="DateTime"/>
<asp:Parameter Name="ReasonID" Type="Int32"/>
<asp:Parameter Name="Notes" Type="String"/>
</UpdateParameters>
</asp:SqlDataSource>
On Button Click codebehind
protected void FvFooter_OnItemCommand(object sender, FormViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "DeleteOrder":
// Confirmation stuff here
break;
case "NewOrder" when Page.IsValid:
Label lblProjectId = (Label)FvHeader.FindControl("LblProjectID");
String strOrderDate = DateTime.Now.ToShortDateString();
FvMatOrdersSQL.InsertParameters.Clear();
FvMatOrdersSQL.InsertParameters.Add("ProjectID", lblProjectId.Text);
FvMatOrdersSQL.InsertParameters.Add("OrderDate", strOrderDate);
FvMatOrdersSQL.Insert();
break;
case "Email" when Page.IsValid:
break;
}
}
OnInserted codebehind
protected void FvMatOrdersSQL_OnInserted(object sender, SqlDataSourceStatusEventArgs e)
{
String strOrderId = e.Command.Parameters["#NewOrderID"].Value.ToString();
Response.Redirect("MatOrderDetails.aspx?OrderID=" + strOrderId);
}
I've tried to base as much of my code on the example here https://msdn.microsoft.com/en-us/library/ms228051.aspx but apparently I'm missing something.
I've put yr code and have created a db close to yr select to figure out yr problem, I have to admit it wasn't easy :) please
change this
FvMatOrdersSQL.InsertParameters.Clear();
FvMatOrdersSQL.InsertParameters.Add("ProjectID", lblProjectId.Text);
FvMatOrdersSQL.InsertParameters.Add("OrderDate", strOrderDate);
To:
FvMatOrdersSQL.InsertParameters["ProjectID"].DefaultValue = lblProjectId.Text;
FvMatOrdersSQL.InsertParameters["OrderDate"].DefaultValue = strOrderDate;
Don't remove the params which you've already created in the UI!

Session variables updating, but not refreshing gridview

I have a GridView which has two session vairables used to filter the select statement (TimeStart and TimeFinish). I have a default value for these, which displays the correct information in the GridView.
I have two ASP TextBoxes with TextMode set to Time which I need to update these values. These update the session variables (have set a label's value to check), but do not update the select statement of my GridView.
I've done something Identical for another GridView on the same page, the only difference being that the session variable in an Int32 and being set from a GridView's IndexChanged event, and am confused as to why it's not working for this one.
Source for GridView:
<asp:GridView ID="gvAvailableVets" runat="server" AutoGenerateColumns="False" DataKeyNames="VetID" DataSourceID="AvailableVetsDataSource">
<Columns>
<asp:BoundField DataField="VetID" HeaderText="VetID" ReadOnly="True" SortExpression="VetID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="MobileNumber" HeaderText="MobileNumber" SortExpression="MobileNumber" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="AvailableVetsDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:VetPracticeConnectionString %>" SelectCommand="SELECT DISTINCT Veternarians.VetID, FirstName, LastName, MobileNumber FROM dbo.Veternarians
INNER JOIN dbo.VetHours
ON Veternarians.VetID = VetHours.VetID
INNER JOIN dbo.Appointments
ON Veternarians.VetID = Appointments.VetID
WHERE #beginTime > VetHours.StartTime
AND #endTime < VetHours.EndTime
AND (#beginTime > Appointments.EndTime
OR #endTime < Appointments.BeginTime) ">
<SelectParameters>
<asp:SessionParameter DefaultValue="9:00" Name="beginTime" SessionField="TimeStart" Type="String" />
<asp:SessionParameter DefaultValue="10:00" Name="endTime" SessionField="TimeFinish" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
C# code behind for the TextBoxes:
protected void txtTimeBegin_TextChanged(object sender, EventArgs e) {
Session["TimeStart"] = txtTimeBegin.Text;
// Used for debugging
lblDebug.Text = Session["TimeStart"].ToString();
}
protected void txtTimeEnd_TextChanged(object sender, EventArgs e) {
Session["TimeFinish"] = txtTimeEnd.Text;
}
Try to rebind your Gridview when any textbox value changed.
protected void txtTimeBegin_TextChanged(object sender, EventArgs e)
{
Session["TimeStart"] = txtTimeBegin.Text;
gvAvailableVets.DataBind();
// Used for debugging
lblDebug.Text = Session["TimeStart"].ToString();
}
protected void txtTimeEnd_TextChanged(object sender, EventArgs e)
{
Session["TimeFinish"] = txtTimeEnd.Text;
gvAvailableVets.DataBind();
}

ASP.Net GridView strange edit behaviour with paging

I have an ObjectDataSource
<asp:ObjectDataSource SelectCountMethod="GetCount" EnablePaging="true" SortParameterName="sortExpression" ID="customersDS" runat="server" SelectMethod="GetList" TypeName="expenses.Classes.ExpenseFactory" DeleteMethod="Delete" UpdateMethod="Update" >
<SelectParameters>
<asp:ControlParameter ControlID="IdHidden" PropertyName="Value" Name="userId" />
<asp:Parameter DbType='Boolean' DefaultValue='false' Name='isExpense' />
<asp:Parameter DbType='Boolean' DefaultValue='false' Name='containRepeated' />
<asp:ControlParameter DbType="Int32" DefaultValue="" ControlID="CategorySelector2" Name="categoryId" />
<asp:ControlParameter DbType="DateTime" DefaultValue="" ControlID="FromSpentDateCalendarBox" Name="from" />
<asp:ControlParameter DbType="DateTime" DefaultValue="" ControlID="ToSpentDateCalendarBox" Name="to" />
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter ControlID="IdHidden" PropertyName="Value" Name="userId" />
<asp:Parameter DbType='Boolean' DefaultValue='false' Name='isExpense' />
</UpdateParameters>
</asp:ObjectDataSource>
connected to a GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AllowPaging="True" AllowSorting="True"
DataSourceID="customersDS" CssClass="gtable sortable width100" DataKeyNames="Id"
AlternatingRowStyle-CssClass="odd" CellPadding="0" GridLines="None" OnPreRender="PreRender"
OnRowDataBound="GridView1_RowDataBound"
>
with edit and delete buttons in a CommandField
<asp:CommandField ItemStyle-Width="75px" HeaderStyle-Font-Bold=true HeaderText="<%$ Resources:Default, Actions %>" EditImageUrl="~/img/edit.png" ButtonType='Image' ShowEditButton="True" UpdateImageUrl="~/img/save.gif" CancelImageUrl="~/img/cancel.png" >
<ControlStyle CssClass="my_edit_buttons" />
</asp:CommandField>
Everything is located inside and UpdatePanel. The GridView and ObjectDataSource support and use paging. Paging works without any problems. The problem is editing. When I click edit on the first page, everything works as expected. When I click edit on the n-th item on the second or other page (greater than one), the GridView switches to the first page and selected the n-th item for editing.
(More concerete example: I switch to the second page, I select the item number 2 on that page to be edited, the GridView switches to the first page and selects the item number 2 (on the first page) to be edited).
Any ideas what may be the problem?
EDIT:
PreRender (setting GridView header):
protected void PreRender(object sender, EventArgs e)
{
try
{
GridView1.UseAccessibleHeader = false;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
catch
{
}
}
RowDataBound (changind delete button to a custom one with configmation prompt|:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// we are using a html anchor and a hidden asp:button for the delete
HtmlAnchor linkDelete = (HtmlAnchor) e.Row.FindControl("linkDelete");
ImageButton btnDelete = (ImageButton) e.Row.FindControl("btnDelete");
string prompt = Resources.Default.DeletePrompt;
linkDelete.Attributes["onclick"] = string.Format(prompt, btnDelete.ClientID);
Expense expense = e.Row.DataItem as Expense;
if (expense!=null)
{
if (expense.SpentDate>DateTime.Now)
{
e.Row.CssClass = "future";
}
}
e.Row.Cells[1].CssClass = e.Row.Cells[4].CssClass = "red";
}

Having trouble using a multiple criteria search bar/button in Site.Master from an SQL server (C# / ASP.Net)

Hey people I'm having a little issue regarding a transfer of variables from Site.Master to another window, the purpose is to make a search function accessed from the whole asp.net web application...
The code which is relevant from Site.Master:
<div class="search">
<asp:Label ID="LandID" runat="server" Text="LandID"/>
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Label ID="CarBrand" runat="server" Text="CarBrand" />
<asp:TextBox ID="txtSearch2" runat="server" />
<asp:Label ID="Model" runat="server" Text="Model"/>
<asp:TextBox ID="txtSearch3" runat="server" />
<asp:Button ID="cmdSearch" runat="server" Text="Search" Style="width: 100px" OnClick="cmdSearch_Click" />
</div>
The Code from Site.Master.Cs:
public static string Text { get; set; }
public static string Text2 { get; set; }
public static string Text3 { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdSearch_Click(object sender, EventArgs e)
{
Text = txtSearch.Text;
Text2 = txtSearch2.Text;
Text3 = txtSearch3.Text;
Response.Redirect("search.aspx");
}
The code from the search.aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged" DataKeyNames="ID">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" InsertVisible="False"
ReadOnly="True" />
<asp:BoundField DataField="LandID" HeaderText="LandID" SortExpression="LandID" />
<asp:BoundField DataField="Bilmaerk" HeaderText="Bilmaerk" SortExpression="Bilmaerk" />
<asp:BoundField DataField="Model" HeaderText="Model" SortExpression="Model" />
<asp:BoundField DataField="Variant" HeaderText="Variant" SortExpression="Variant" />
<asp:BoundField DataField="StartYear" HeaderText="StartYear" SortExpression="StartYear" />
<asp:BoundField DataField="SlutYear" HeaderText="SlutYear" SortExpression="SlutYear" />
<asp:BoundField DataField="Volumen" HeaderText="Volumen" SortExpression="Volumen" />
<asp:BoundField DataField="MaxDrej" HeaderText="MaxDrej" SortExpression="MaxDrej" />
<asp:BoundField DataField="AntalCylindre" HeaderText="AntalCylindre" SortExpression="AntalCylindre" />
<asp:BoundField DataField="TopHast" HeaderText="TopHast" SortExpression="TopHast" />
<asp:BoundField DataField="Acceleration" HeaderText="Acceleration" SortExpression="Acceleration" />
<asp:BoundField DataField="Beskrivelse" HeaderText="Beskrivelse" SortExpression="Beskrivelse" />
<asp:BoundField DataField="Effekt" HeaderText="Effekt" SortExpression="Effekt" />
<asp:BoundField DataField="Picture" HeaderText="Picture" SortExpression="Picture" />
</Columns>
</asp:GridView>
<selectparameters>
<asp:ControlParameter ControlID="<%=Text1 %>"></asp:ControlParameter>
<asp:ControlParameter ControlID="<%=Text2 %>"></asp:ControlParameter>
<asp:ControlParameter ControlID="<%=Text3 %>"></asp:ControlParameter>
</selectparameters>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CarConnectionString %>"
SelectCommand="SELECT * FROM [Bil] WHERE (([LandID] LIKE '%' +#LandID+ '%') AND ([Bilmaerk] LIKE '%' +#Bilmaerk+ '%') AND ([Model] LIKE '%' +#Model+ '%'))">
<SelectParameters>
<asp:ControlParameter ControlID="Text1" Name="LandID" PropertyName="Text" Type="String"
DefaultValue="%" />
<asp:ControlParameter ControlID="Text2" Name="Bilmaerk" PropertyName="Text" Type="String"
DefaultValue="%" />
<asp:ControlParameter ControlID="Text3" Name="Model" PropertyName="Text" Type="String"
DefaultValue="%" />
</SelectParameters>
</asp:SqlDataSource>
the Relevant code from search.aspx.cs:
public partial class search : System.Web.UI.Page
{
protected string Text1 { get; set; }
protected string Text2 { get; set; }
protected string Text3 { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Text1 = SiteMaster.Text;
Text2 = SiteMaster.Text2;
Text3 = SiteMaster.Text3;
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Constructor.SelectedCar = GridView1.SelectedRow.Cells[1].Text;
Response.Redirect("Selected.aspx");
}
}
On page load or page prerender of the master based on the life cycle of your page, initially store the values the textboxes of different search fields into the session variables respectively.
And then you can access these variables on search button click then you can proceed further of the basic steps like going to database and search the relevant fields and so on.
By using these session variables you can access them anywhere in any page untill and unless you change the values....
public void search(object sender ,EventArgs e)
{
string Search = session["search"].toString();
Search = Search + "%";
SqlDataSource1.SelectParameters.Clear();
SqlDataSource1.SelectParameters.Add("search", Search);
Search = "%" + Search;//for user name ,user email,languages made the search criteria as anywhere in the word for others it is starting letter
SqlDataSource1.SelectParameters.Clear();//again we have to clear and add since search is changed
SqlDataSource1.SelectParameters.Add("search", Search);
SqlDataSource1.SelectCommand = "SELECT [UserID], [UserName], [UserEmail], [UserContact], [UserAddress], [Gender], [Languages], [Status], [Passwords],[Image] FROM [Users_raghu] where [UserName] like #search";
}
This is the sample you can refer here I have given you only one search variable in your case you have to take 3 session variables and proceed further
Hope this helps :D
why dont you use session to transfer data from one page to another..??
its quite simple ,
//this is how you will create the Session on master page
{
Session["text"] = txtearch.Text;
Session["Text2"] = txtSearch2.Text;
Session["Text3"] = txtSearch3.Text;
}
on another page just use it like
{
string a = Session["text"].ToString();
string b = Session["text2"].ToString();
string c = Session["text3"].ToString();
}
Try use HTTP GET method like code bellow:
On your Site.Master.Cs
protected void cmdSearch_Click(object sender, EventArgs e)
{
Text = txtSearch.Text;
Text2 = txtSearch2.Text;
Text3 = txtSearch3.Text;
Response.Redirect(string.Format("search.aspx?txtSearch={0}&txtSearch2={1}&txtSearch3={2}", Text, Text2, Tex3));
}
On your search.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Text1 = Request["txtSearch"];
Text2 = Request["txtSearch2"];
Text3 = Request["txtSearch3"];
}
Also you can add GET parameter to your master page control by call:
(Master.FindControl("txtSearch") as TextBox).Text = Request["txtSearch"];

Categories