按名字和姓氏搜索数据库 [英] Search Database by First and Last Name
问题描述
我将 ASP.NET 与 C# 和 subsonic 一起使用.我正在尝试按名字和姓氏在文本字段上设置搜索.
I am using ASP.NET with C# and subsonic. I am trying to setup a search on a text field by first and last name.
First or Last Name: <asp:TextBox ID="txtSearchName" runat="server"></asp:TextBox>
<asp:linkButton runat="server" Text="Send" onclick="btnSubmit_Click" />
<asp:GridView
border="0"
cellpadding="3"
cellspacing="3"
ShowHeader="True"
allowsorting="true"
ID="GridView1"
runat="server"
AutoGenerateColumns="false"
Visible="false"
AllowPaging="True"
PageSize="10"
PagerStyle-Mode="NumericPages"
OnPageIndexChanging="GridView1_PageIndexChanging"
>
在后面的代码中,我有这个:
In the code behind, I have this:
private void BuildGridView1()
{
GridView1.DataSource = new Select(PastAwardName.Schema.TableName + ".*", PastAwardType.Schema.TableName + ".*")
.From(PastAwardName.Schema)
.InnerJoin(PastAwardType.Schema.TableName, PastAwardType.Columns.VolID, PastAwardName.Schema.TableName, PastAwardName.Columns.VolID)
.Where(PastAwardName.Columns.LName).IsEqualTo(this.txtSearchName.Text)
.Or(PastAwardName.Columns.FName).IsEqualTo(this.txtSearchName.Text)
.OrderAsc(PastAwardType.Columns.AwardYear)
.ExecuteDataSet();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BuildGridView1();
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
如果您输入名字或姓氏,这会起作用,但我希望能够从一个文本字段同时搜索它们.这可能吗?
This works if you enter either the first or last name, but I want to be able to search for them both at the same time from one text field. Is this possible?
推荐答案
您应该能够构建您的查询,然后根据您是否有多个名称来附加 Or/And 限制.以下应该可以工作,但您应该注意边缘情况,例如双重姓名、用户输入中间名等,会引起您的注意:
You should be able to build your query and then append the Or/And restrictions based on whether you have more than one name. The following should work but you should be aware that edge cases like double-barelled names, a user entering a middle name etc. will catch you out:
private void BuildGridView1()
{
string[] names = this.txtSearchName.Text.Split(" ".ToCharArray());
SqlQuery query = DB.Select(PastAwardName.Schema.TableName + ".*", PastAwardType.Schema.TableName + ".*")
.From(PastAwardName.Schema)
.InnerJoin(PastAwardType.Schema.TableName, PastAwardType.Columns.VolID, PastAwardName.Schema.TableName, PastAwardName.Columns.VolID)
.Where(PastAwardName.Columns.FName).IsEqualTo(names[0])
if(names.Length > 1)
query = query.And(PastAwardName.Columns.LName).IsEqualTo(names[1])
else
query = query.Or(PastAwardName.Columns.LName).IsEqualTo(names[0]
GridView1.DataSource = query.OrderAsc(PastAwardType.Columns.AwardYear)
.ExecuteDataSet();
}
这篇关于按名字和姓氏搜索数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!