如果在c#中按名称搜索,如何从表中选择行

本文关键字:选择 搜索 如果 | 更新日期: 2023-09-27 18:26:37

这是我的输出页面的屏幕截图。

我创建了一个下拉列表,其中包含,1.以2开头,3.以结束。

我需要根据上述条件搜索记录。

我已经创建了学生表,它有名称、班级、部分、地址、图片和课外活动。

现在我需要根据名称是否包含、以开头和以结尾来搜索记录。

例如,如果我在下拉列表中选择以开头,并在文本框中键入"S"。它应该显示记录名称以"S"开头的记录。

为此我该怎么办,?有人能给我指路吗?

如有任何帮助,我们将不胜感激。

谢谢。

searchrecord_click:的代码

SqlCommand com = new SqlCommand("sp_searchedstudentrecords", con);
                com.CommandType = CommandType.StoredProcedure;
                SqlParameter retval = new SqlParameter("@condition", SqlDbType.VarChar, 20);
                SqlParameter retval1 = new SqlParameter("@searchtext", SqlDbType.VarChar, 50);
                retval.Direction = ParameterDirection.ReturnValue;
                com.Parameters.Add(retval);                
                string ReturnValue = retval.Value.ToString();
                SqlDataAdapter adp = new SqlDataAdapter(com);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                tblid.Visible = true;
                com.Parameters.AddWithValue("@Name", Textusername.Text.Trim());
                com.Parameters.AddWithValue("@Class", Textclass.Text.Trim());
                com.Parameters.AddWithValue("@Section", Textsection.Text.Trim());
                com.Parameters.AddWithValue("@Address", Textaddress.Text.Trim());
                com.Parameters.AddWithValue("@Email", Textemail.Text.Trim());
                com.Parameters.AddWithValue("@Mobilenum", Textmobilenum.Text.Trim());
                com.Parameters.AddWithValue("@EC_id", Textcurricular.SelectedValue);
com.ExecuteNonQuery();

我把写存储过程弄糊涂了。

如果在c#中按名称搜索,如何从表中选择行

您的查询必须是:

开始时:

select name, section, class from students where name like @variable+'%'

对于包含

select name, section, class from students where name like '%'+@variable+'%'

并完成

select name, section, class from students where name like '%'+@variable

这三个查询必须写入存储过程中的IF-ELSE中。

试试这个

CREATE PROCEDURE sp_searchedstudentrecords
@condition varchar(20),
@searchText varchar(10)
AS
if(@condition ='STARTS WITH')
SELECT * from tblStudents where NAME like @searchText+'%'
else if(@condition='Ends with')
SELECT * from tblStudents where NAME like '%'+@searchText
else
SELECT * from tblStudents where NAME like '%'+@searchText+'%'

以下是如何调用它并将其绑定到gridview

MySqlCommand com = new MySqlCommand("sp_searchedstudentrecords", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@condition",condition);
com.Parameters.AddWithValue("@searchtext",searchtext);                
MySqlDataAdapter adp = new MySqlDataAdapter(com);
DataSet ds = new DataSet();
adp.Fill(ds);
grdStudent.DataSource=ds.Tables[0];
grdStudent.DataBind();

您需要从调用此方法的位置传递conditionsearchtext

此外,您正在使用mysql,因此需要使用MySqlCommandMySqlDataAdapter,而不是SqlCommandSqlDataAdapter