Introduction: In
this article today I will explain Like linq query example and bind gridview.
Description:
In the previous article I have explained Server side validation in MVC Razor using data annotation, URL routing in asp.net website, Populate Dropdown List dynamically using Asp.net MVC Razor, Code First migration in asp.net MVC 4, Populate Cascading Dropdown List in Asp.net MVC4 using Json and Jquery and What is Asp.net MVC? Its advantages and disadvantges.
I have a table Product:
ID
|
int
|
PRODUCT_NAME
|
varchar(50)
|
DESCRIPTION
|
varchar(50)
|
PRODUCT_PRICE
|
int
|
I want to search products on product name and display the
matched results in gridview.
Add a new webform to project and design the .aspx page as
shown:
<fieldset style="width:420px">
<legend>Like with Linq query Example</legend>
<table width="100%">
<tr><td>Enter Product Name:</td><td><asp:TextBox ID="txtsearch" runat="server"></asp:TextBox></td></tr>
<tr><td></td><td><asp:Button ID="btnserach"
runat="server"
onclick="btnserach_Click"
Text="Button"
/></td></tr>
<tr><td></td>
<table>
<tr>
<asp:GridView ID="GridView1"
runat="server"
EmptyDataText="No
records Found"
ShowHeaderWhenEmpty="True"
AutoGenerateColumns="False"
CellPadding="4"
ForeColor="#333333"
GridLines="None"
Width="408px">
<AlternatingRowStyle
BackColor="White"
ForeColor="#284775"
/>
<Columns>
<asp:BoundField DataField="PRODUCT_NAME"
HeaderText="Product
Name" />
<asp:BoundField DataField="DESCRIPTION"
HeaderText="Description"
/>
<asp:BoundField DataField="PRODUCT_PRICE"
HeaderText="Price"
/>
</Columns>
<EditRowStyle BackColor="#999999"
/>
<FooterStyle BackColor="#5D7B9D"
Font-Bold="True"
ForeColor="White"
/>
<HeaderStyle BackColor="#5D7B9D"
Font-Bold="True"
ForeColor="White"
/>
<PagerStyle BackColor="#284775"
ForeColor="White"
HorizontalAlign="Center"
/>
<RowStyle BackColor="#F7F6F3"
ForeColor="#333333"
/>
<SelectedRowStyle
BackColor="#E2DED6"
Font-Bold="True"
ForeColor="#333333"
/>
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle
BackColor="#506C8C"
/>
<SortedDescendingCellStyle
BackColor="#FFFDF8"
/>
<SortedDescendingHeaderStyle
BackColor="#6F8DAE"
/>
</asp:GridView></tr>
</table></tr>
</table>
</fieldset>
On button click write the given code on .aspx.cs page:
DataClasses1DataContext db = new
DataClasses1DataContext();
protected void
btnserach_Click(object sender, EventArgs e)
{
var product = from p in db.PRODUCTs
where p.PRODUCT_NAME.Contains(txtsearch.Text.Trim())
select p;
GridView1.DataSource = product;
GridView1.DataBind();
}
OR
using System.Data.Linq.SqlClient;
protected void
btnserach_Click(object sender, EventArgs e)
{
var product = from p in db.PRODUCTs
where
SqlMethods.Like(p.PRODUCT_NAME, "%" + txtsearch.Text + "%")
select p;
GridView1.DataSource = product;
GridView1.DataBind();
}
Build the project and run.
No comments:
Post a Comment