我有一个TextBox和一个搜索按钮。用户将多个逗号分隔值放在一个TextBox(例如111,222,333)中,这些值存储在一列(ID)中,然后通过MS Access表获取网格视图中的所有记录。
表名:mytable
字段:
ID name phno
111 saket 8097626799
222 deepak 9167480458
333 abhi 9229457891
444 rajesh 9826789561
555 sudhir 9167849503
输出:
ID name phno
111 saket 8097626799
222 deepak 9167480458
333 abhi 9229457891
答案 0 :(得分:1)
以下对文本框中的文本进行断言,请参阅注释。如果所有断言/验证都通过,变量whereCondition将包含示例SQL语句。
private void button1_Click(object sender, EventArgs e)
{
string whereStatement = "";
// ensure we have something to work with
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
// Are there commas
if (textBox1.Text.Contains(","))
{
string textValue = textBox1.Text.TrimEnd();
// make sure there is no trailing commas
if (textValue.Last() != ',')
{
string[] parts = textBox1.Text.Split(',');
int badCount = 0;
int testValue = 0;
// see if all values are int
foreach (string item in parts)
{
if (!int.TryParse(item, out testValue))
{
badCount += 1;
}
}
if (badCount == 0)
{
string whereCondition = "ID = " + textValue.Replace(",", " OR ID = ");
whereStatement = string.Format("SELECT [Name], phno WHERE {0} FROM mytable", whereCondition);
}
}
}
else
{
// one id
whereStatement = string.Format("SELECT [Name], phno WHERE ID = {0} FROM mytable", textBox1.Text);
}
}
if (!string.IsNullOrWhiteSpace(whereStatement))
{
MessageBox.Show(whereStatement);
}
else
{
MessageBox.Show("Invald data");
}
}
答案 1 :(得分:0)
我有另一个代码 它的工作原理 c#CODE
protected void Page_Load(object sender,EventArgs e) { if(!this.IsPostBack) { this.BindGrid(); } } protected void搜索(对象发送者,EventArgs e) { this.BindGrid(); }
private void BindGrid()
{
//string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string constr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\WebSite1\App_Data\MPHS.mdb";
using (OleDbConnection con = new OleDbConnection(constr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
string resultCont = string.Empty;
if (!string.IsNullOrEmpty(txtSearch.Text))
{
string[] contactNames = txtSearch.Text.Trim().Split(',');
foreach (string cont in contactNames)
{
if (!string.IsNullOrEmpty(cont))
{
resultCont = resultCont + ",'" + cont + "'";
}
}
resultCont = resultCont.Remove(0, 1);
cmd.CommandText = "SELECT * FROM myTable WHERE Docnum IN (" + resultCont + ")";
}
else
{
cmd.CommandText = "SELECT * FROM myTable";
}
DataTable dt = new DataTable();
using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}