LIKE in "where" LINQ statement causes error [duplicate] - c#

This question already has answers here:
How to use SQL 'LIKE' with LINQ to Entities? [duplicate]
(11 answers)
Linq LIKE functionality
(1 answer)
Closed 7 years ago.
ProductModel.cs: (class)
public List<Product> GetSearchedProduct (string Name)
{
try
{
using (garagedbEntities db = new garagedbEntities())
{
List<Product> products = (from x in db.Products
where x.Name LIKE #txtSearch
select x).ToList();
return products;
}
}
catch (Exception)
{
return null;
}
}
search.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Button" OnClick="btnSearch_Click" />
<br />
<asp:Panel ID="pnlProducts" runat="server">
<br />
</asp:Panel>
<div style="clear:both"></div>
This is my search.aspx file. Actually I want to get the name of the product from TextBox then pass it to method which retrieves the products.

In linq you should use Contains:
List<Product> products = (from x in db.Products
where x.Name.Contains(Name)
select x).ToList();
Edit: To use method you should create a new instance of ProductModel and then call the GetSearchedProduct method and send the txtSearch as a parameter to it. Like this:
protected void btnSearch_OnClick(object sender, EventArgs e)
{
ProductModel pr = new ProductModel();
var result = pr.GetSearchedProduct(txtSearch.Text);
}

Related

Delete Button within Repeater does not exist within current context

===================
UPDATE: 29/06/2017
I am trying to get the delete button within my repeater control to function as intended. The aim is to get the button to "fire" the stored procedure within my MSSQL database.
I would like to thank Win for his in-depth response although I am still struggling to resolve the issue. I accept that I was perhaps unable to articulate my question correctly in the first instance. I have therefore edited my post to show the code I have now. I am confident that I am close to cracking the issue and would sincerely appreciate any assistance.
Code within my *.*aspx page:
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM
[Comments] WHERE ([Ad_ID] = #Ad_ID) ORDER BY [CommentCreationDateTime] ASC">
And further down the *.*aspx page:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource2"
Visible="True" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<table id="displayCommentsTable" class="displayCommentsTable">
<tr class="displayCommentsTable"><td class="displayCommentsTable">
<asp:ImageButton ID="deleteCommentImageButtonReal" runat="server"
class="rightCross" ImageUrl="images/Red-Cross-Mark-PNG.png"
OnClientClick="return confirm('Are you sure you wish to delete this
comment?');" Height="11" Width="11" CommandName="Delete"
CommandArgument='<%# Eval("Comment_ID") %>' /><%# Eval("CommenterName") %>
commented on <%# Eval("CommentCreationDateTime", "{0:d/M/yyyy <i> hh:mm:ss
tt}") %>
</td></tr>
<tr class="displayCommentsTable"><td class="displayCommentsTable"><%#
Eval("CommentText") %><br /></td></tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
And finally, my code behind where the magic should be happening but isn't:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
DeleteCommentById(Convert.ToInt32(e.CommandArgument))
}
}
private void DeleteCommentById(int Comment_ID)
{
SqlConnection conn;
SqlCommand deleteCommentById;
string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
deleteCommentById = new SqlCommand("usp_deleteCommentById", conn);
deleteCommentById.CommandType = System.Data.CommandType.StoredProcedure;
deleteCommentById.Parameters.Add("#Comment_ID", System.Data.SqlDbType.Int);
deleteCommentById.Parameters["#Comment_ID"].Value = Comment_ID;
conn.Open();
deleteCommentById.ExecuteNonQuery();
conn.Close();
}
It is perhaps worth mentioning that if I "hard code" the line I am attempting to delete then it works. For example, if I used the following within my delete button:
CommandArgument='44'
then the stored procedure would fire and affect line 44 as intended.
Easiest way is to use ItemCommand event.
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="RepeaterDemo.aspx.cs" Inherits="DemoWebForm.RepeaterDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Repeater ID="Repeater1" OnItemCommand="Repeater1_ItemCommand" runat="server">
<ItemTemplate>
<p>
<%#Eval("Name") %>
<asp:ImageButton CommandArgument='<%# Eval("Id") %>' runat="server"
ImageUrl="~/Images/Delete.png" CommandName="Delete" />
</p>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DemoWebForm
{
public partial class RepeaterDemo : System.Web.UI.Page
{
public class Comment
{
public int Id { get; set; }
public string Name { get; set; }
}
public static IList<Comment> Comments = new List<Comment>
{
new Comment {Id = 1, Name = "One"},
new Comment {Id = 2, Name = "Two"},
new Comment {Id = 3, Name = "Three"}
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Repeater1.DataSource = Comments;
Repeater1.DataBind();
}
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int id = Convert.ToInt32(e.CommandArgument);
var comment = Comments.FirstOrDefault(c => c.Id == id);
Comments.Remove(comment);
Repeater1.DataSource = Comments;
Repeater1.DataBind();
}
}
}
}
In what event are you trying to access the repeater button?
You will need to try to find the control inside the repeater item.
For eg:
Button btn1 = (Button)rptItem.FindControl("btn1");
Everything was working fine but as I had not specified to only return results that had not been soft deleted, everything was getting returned. Noob mistake, learnt something for the future!

Set checkbox as checked in Repeater/CheckboxList

I'm using a Repeater to show some data coming from a web service.
My Repeater structure is:
<asp:Repeater ID="rptgrp" runat="server">
<ItemTemplate>
<asp:CheckBoxList ID="chkBoxListGoup" runat="server"
DataSource='<%# DataBinder.Eval(Container.DataItem, "Titles")%>'
DataTextField="Title"
DataValueField="IDTitle">
</asp:CheckBoxList>
</ItemTemplate>
</asp:Repeater>
Now, my web service returns these fields in "Titles":
1) Title
2) IDTitle
3) isUserTitle
Now, I would like to set checked a checkbox when isUserTitle is = 1.
How can I do that?
You can find checkboxlist as follows
Find checkboxlist in itemdatabound,
check item text of every checkboxlist using loop,
select the item whose text is 1
Protected void Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
CheckBoxList chklst = (CheckBoxList)e.Item.FindControl("chkBoxListGoup");
for (int i = 0; i < chk.Items.Count; i++)
{
if (chk.Items[i].Text == "1")
{
chk.Items[i].Selected = true;
}
}
}
}
Try changing <asp:CheckBoxList ID="chkBoxListGoup" runat="server"
to
<asp:CheckBoxList ID="chkBoxListGoup" Checked='<%#Eval("Flag")%>' runat="server"
Flag being your Column..
Then in your method or event handler you want to run some code to say if this value = 1 checked, elseif value = 0 unchecked...
Here is sample code that demonstrates the idea:
Code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using WebApp.RepeaterCheckboxList.TODODatasetTableAdapters;
namespace WebApp.RepeaterCheckboxList
{
public partial class WebForm1 : System.Web.UI.Page
{
IEnumerable<TODODataset.TasksViewRow> view;
IEnumerable<TODODataset.TasksViewRow> subview;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TasksViewTableAdapter adp = new TasksViewTableAdapter();
var dt = adp.GetData();
view = dt.AsEnumerable();
var names = (from x in view
select new
{
Person = x.Name,
ID = x.PersonID
}).Distinct();
DataList1.DataSource = names;
DataList1.DataBind();
}
}
protected void CheckBoxList1_DataBound(object sender, EventArgs e)
{
CheckBoxList theList = (CheckBoxList)sender;
var person = ((DataListItem)theList.Parent).DataItem as dynamic;
var name = person.Person;
var id = person.ID;
var vw = subview;
for (int i = 0, j = vw.Count(); i < j; i++)
{
var task = vw.ElementAt(i);
theList.Items[i].Selected = task.Completed;
}
}
protected IEnumerable<TODODataset.TasksViewRow> GetTasks(object data)
{
var vw = data as dynamic;
return subview = (from x in view
where x.PersonID == vw.ID
select x);
}
}
}
Aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.RepeaterCheckboxList.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<div style="padding:5px">
<h3><%# Eval("Person") %></h3>
<div>
<asp:CheckBoxList OnDataBound="CheckBoxList1_DataBound" ID="CheckBoxList1"
runat="server"
DataTextField="TaskDesc" DataValueField="TaskID"
DataSource="<%# GetTasks(Container.DataItem) %>"></asp:CheckBoxList>
</div>
</div>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
If you are interested in the data, click here
Try just setting the Checked value to the object being Evaled.
<asp:Repeater ID="rptgrp" runat="server">
<ItemTemplate>
<asp:CheckBoxList ID="chkBoxListGoup" runat="server"
Checked=<%# Eval("isUserTitle") %>>
</asp:CheckBoxList>
</ItemTemplate>
</asp:Repeater>

How Can I Hide or Show Asp:Content using a Session in If statement

At my Production.aspx Web Form I have this code:
<%# Page Title="" Language="C#" MasterPageFile="~/Index.Master" AutoEventWireup="true" CodeBehind="Production.aspx.cs" Inherits="WebPortal.Production" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h3>PRODUCTION SITE</h3>
<img src="" alt="Production Logo" height="350" width="350" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="10pt" Height="187px" Width="235px">
<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />
</asp:Login>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder3" runat="server">
</asp:Content>
And at my Production.aspx.cs Web Form i Have this Code:
namespace WebPortal
{
public partial class Production : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
var GetSession = Session["Counter"];
if (Convert.ToInt32(GetSession) == 1)
{
// Show Content 1
}
else if (Convert.ToInt32(GetSession) == 2)
{
// Show Content 2
}
else
{
// Show Content 3
}
}
catch (Exception ex)
{
// MessageBox.show(ex.message.tostring());
}
}
}
}
how can i try to hide a content based on the session value like when a user try to login by its account and based on its access level he gets a 1 which trigger the if statement then based on its value on what content to show..
Put div into every content and show/hide div like folowing:
ASPX:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div runat="server" id="div1">
<h3>PRODUCTION SITE</h3>
<img src="" alt="Production Logo" height="350" width="350" />
</div>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<div runat="server" id="div2">
<asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="10pt" Height="187px" Width="235px">
<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />
</asp:Login>
</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder3" runat="server">
<div runat="server" id="div3">
<p>q3</p>
</div>
</asp:Content>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
div1.Visible = div2.Visible = div3.Visible = false;
if (Session["Counter"] != null)
{
int GetSession = (int)Session["Counter"];
if (GetSession == 1)
div1.Visible = true;
else if (GetSession == 2)
div2.Visible = true;
else
div3.Visible = true;
}
else
div3.Visible = true;
}
You're probably best using different nested master pages for different access levels as suggested above, though if you're stuck with what you've got you could use a multiview control on the master with three views, each holding one of the placeholders.
Add a MasterType directive to your content pages so you can reference the Master page then set the Multiview active index as required.
Code is not tested, just a rough idea - I'd use a switch block instead of 'if' myself.
protected void Page_Load(object sender, EventArgs e)
{
MultiView mv = (MultiView)Master.FindControl("multiView1");
var GetSession = Session["Counter"];
if (Convert.ToInt32(GetSession) == 1)
{
mv.ActiveViewIndex = 0
}
else if (Convert.ToInt32(GetSession) == 2)
{
mv.ActiveViewIndex = 1
}
else
{
mv.ActiveViewIndex = 2
}
}

Unable to get textbox even when ID is defined

I am currently creating a page that a user will be able to input information and on submit it should save this information to a text file, however I seem to be unable to obtain the textbox as it appears to be undefined even when an ID is set on it, could someone please explain what I am doing wrong? As it seems to be working correctly with my btnSave method.
Backend C#:
public partial class Green_FreeShipping : System.Web.UI.Page
{
private static readonly string FILE_PATH = "~/TextFiles/Notes.txt";
private void GetNote()
{
using (TextReader tr = new StreamReader(MapPath(FILE_PATH)))
{
txtNote.Text = tr.ReadToEnd();
}
}
private void SaveNote()
{
using (TextWriter tw = new StreamWriter(MapPath(FILE_PATH)))
{
tw.Write(txtNote.Text);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetNote();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
this.SaveNote();
this.GetNote();
}
}
ASP.NET code:
<%# Page Language="C#" MasterPageFile="~/admin/masters/admin.master" autoeventwireup="true" inherits="TextBox_ReadWriteToTextFile" Title="Green & Free shipping amounts" codefile="~/admin/bespoke/Green-FreeShipping.aspx.cs"%>
<%# Register TagPrefix="web" Assembly="website.Web" Namespace="website.Web" %>
<%# Register TagPrefix="sales" Assembly="website.site.Web" Namespace="website.site.Web.Sales" %>
<%# Register TagPrefix="ecom" Namespace="website.site.Web" Assembly="website.site.Web" %>
<asp:Content ID="TitleContent" ContentPlaceHolderID="TitlePlaceHolder" runat="Server">
<title>Shopfront - Green and Free shipping amounts</title>
</asp:Content>
<asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="Server">
<div style="margin-bottom: 20px;">
<asp:textbox id="txtNote" runat="server" rows="5" textmode="MultiLine" width="200px" />
</div>
<asp:button id="btnSave" runat="server" onclick="btnSave_Click" text="Save" />
</asp:content>
Your asp should inherit 'Green_FreeShipping' so that the c# can have access to the controls contained in it.

Display data on form and update form asynchronously

What is the best way to approaching this? I have a text box where Teachers enter Student ID and I want to display student information based on the id entered. Once the student info is displayed, I have a drop down list which populates with a list which lists all the classes that student is enrolled in. Once a course is selected from that drop down list I want to display students progress on the form in a particular section on the form. How can I approach this? Here is What I have so far:
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Student.Models;
namespace Student.Controllers
{
public class StudentFormController : Controller
{
//
// GET: /StudentForm/
public ActionResult Index()
{
return View("StudentForm");
}
public ActionResult DisplayStudentDetails(string StudentId)
{
StudentDataContext db = new StudentDataContext();
var StudentName = (from p in db.vwStudent.Where(a => a.StudentID == StudentId)
group p by p.StudentName into g
select g.Key).FirstOrDefault();
var StudentClassList = (from p in db.vwStudent.Where(a => a.StudentID == StudentId)
group p by p.ClassID into g
select g.Key).ToList();
ViewData["StudentName"] = StudentName;
ViewData["StudentClassList "] = StudentClassList ;
return View("StudentForm");
}
public ActionResult DisplayClassDetails(string StudentId, string ClassId)
{
StudentDataContext db = new StudentDataContext();
ViewData.Model = (from p in db.vwStudentProgress.Where(a => a.StudentID == StudentId && a.ClassID == ClassId);
return View("LPForm");
}
}
}
View(Form):
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content3" ContentPlaceHolderID="TitleContent" runat="server">
Student Form
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="MainContent" runat="server">
<form id="form2" method="get" action="/StudentForm/DisplayStudentDetails/" runat="server">
<div style="text-align: left; height: 202px;">
<asp:ScriptManager ID="ScriptManager2" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
Student Id:<input type="text" name="id" value="<%=HttpContext.Current.Request.QueryString["StudentId"]%>" /><br />
Student Name:<input type="text" name="StudentName" value="<%=ViewData["ShortName"]%>" /><br />
Classes Enrolled in:
<select name="Classes">
<%if (ViewData["Classes"] != null)
{%>
<% foreach (int? Classes in (List<int?>)ViewData["Classes"])
{%>
<option><%=Classes%></option>
<%}%>
<%}%>
</ContentTemplate>
</asp:UpdatePanel>
<input type="submit" value="Display Student Details"/>
</div>
</form>
</asp:Content>
What is the best way to approaching this?
Simple answer is AJAX. Don't try to use update panels in an ASP.NET MVC application. Use jquery to male ajax calls and update portions of your page.
Once a course is selected from that drop down list I want to display
students progress on the form in a particular section on the form. How
can I approach this?
Basically you should bind to the change event of the dropdown through jquery and call an action that returns a partial view.
Use html helpers to create textboxes, form and other stuff and avoid using the html elements directly.

Categories