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

时间:2015-12-14 10:11:20

标签: c# mysql

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

我已经创建了下拉列表,其中包含1.starts,其中2.ends为和3.contains。

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

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

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

例如,如果我选择以下拉列表开头,则在文本框中输入“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();

我对写存储过程感到困惑。

2 个答案:

答案 0 :(得分:2)

您的查询必须是:

首先:

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

For contains

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

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

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

答案 1 :(得分:1)

试试这个

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