Hi makumbi ,
Please refer below sample code.
Database
I have create a database name Files.
CREATE TABLE [dbo].[Files]
(
[FieldId] INT IDENTITY(1,1) PRIMARY KEY,
[Name] VARCHAR(100) NOT NULL,
[Path] VARCHAR(100) NOT NULL
)
HTML
<div class="container py-4">
<h5 class="text-center text-uppercase">DataList control in asp.net</h5>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="OnSearch" />
<br /><br />
<asp:DataList ID="DataList1" runat="server" CssClass="row">
<ItemTemplate>
<div class="row productList">
<div class="col-4">
<img alt="" width="250" src='<%#Eval("Path")%>' />
</div>
<div class="col-8">
<h4><%#Eval("FileId")%></h4>
<h6><%#Eval("Name")%></h6>
</div>
</div>
</ItemTemplate>
</asp:DataList>
</div>
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindDataList();
}
}
private void BindDataList(string name = null)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string qry = "SELECT * FROM Files WHERE Name LIKE @Name + '%' OR @Name IS NULL";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(qry, con))
{
if (!string.IsNullOrEmpty(name))
{
cmd.Parameters.AddWithValue("@Name", name);
}
else
{
cmd.Parameters.AddWithValue("@Name", DBNull.Value);
}
con.Open();
DataList1.DataSource = cmd.ExecuteReader();
DataList1.DataBind();
con.Close();
}
}
}
protected void OnSearch(object sender, EventArgs e)
{
this.BindDataList(txtName.Text);
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindDataList()
End If
End Sub
Private Sub BindDataList(Optional ByVal name As String = Nothing)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim qry As String = "SELECT * FROM Files WHERE Name LIKE @Name + '%' OR @Name IS NULL"
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(qry, con)
If Not String.IsNullOrEmpty(name) Then
cmd.Parameters.AddWithValue("@Name", name)
Else
cmd.Parameters.AddWithValue("@Name", DBNull.Value)
End If
con.Open()
DataList1.DataSource = cmd.ExecuteReader()
DataList1.DataBind()
con.Close()
End Using
End Using
End Sub
Protected Sub OnSearch(ByVal sender As Object, ByVal e As EventArgs)
Me.BindDataList(txtName.Text)
End Sub
Screenshot