我想使用两个不同的文本框来过滤数据库中的信息,以显示棒球运动员的平均分数。选择0,3到0.4的示例应该显示具有这些数字之间分数的玩家。
什么不起作用的是以下代码:
// Search for player, working
private void button1_Click(object sender, EventArgs e)
{
view.RowFilter = "LastName like '%" + textBox1.Text + "%'";
if (textBox1.Text == "") view.RowFilter = string.Empty;
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable datatable = new DataTable();
SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mattias\Dropbox\C#\Database\Baseball.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
connection.Open();
datatable.Load(new SqlCommand("select * from players", connection).ExecuteReader());
dataGridView1.DataSource = view = datatable.DefaultView;
connection.Close();
}
// This button is not working
private void button2_Click(object sender, EventArgs e)
{
decimal minimum = Convert.ToDecimal(textBox2.Text);
decimal maximum = Convert.ToDecimal(textBox3.Text);
// Should display players with different scores
view.RowFilter = String.Format("BattingAverage >= {0} AND BattingAverage <= {1}"
, minimum, maximum);
if (textBox2.Text == "") view.RowFilter = string.Empty;
if (textBox3.Text == "") view.RowFilter = string.Empty;
}
答案 0 :(得分:0)
RowFilter
不支持BETWEEN
运算符。它也不支持像你这样的完整的SQL查询。但是,您可以在那里指定WHERE
- 子句来过滤视图的行:
view.RowFilter = String.Format(CultureInfo.InvariantCulture.NumberFormat,
"BattingAverage >= {0} AND BattingAverage <= {1}", minimum, maximum);
我在InvariantCulture.NumberFormat
中使用String.Format
来确保RowFilter
中所需的英文格式(点为小数点分隔符)。
请注意,您还使用撇号包装值,这些数字不允许使用数字,并且您使用textBox2.Text
作为最小和最大值的输入。
答案 1 :(得分:0)
现在可以通过添加CultureInfo来实现。 //搜索播放器,正在工作 private void button1_Click(object sender,EventArgs e) { view.RowFilter =“LastName like'%”+ textBox1.Text +“%'”; if(textBox1.Text ==“”)view.RowFilter = string.Empty; }
private void Form1_Load(object sender, EventArgs e)
{
DataTable datatable = new DataTable();
SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mattias\Dropbox\C#\Database\Baseball.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
connection.Open();
datatable.Load(new SqlCommand("select * from players", connection).ExecuteReader());
dataGridView1.DataSource = view = datatable.DefaultView;
connection.Close();
}
// 正在使用CultureInfo private void button2_Click(object sender,EventArgs e) { decimal minimum = Convert.ToDecimal(textBox2.Text); decimal maximum = Convert.ToDecimal(textBox3.Text); //应该显示不同分数的玩家 view.RowFilter = String.Format(CultureInfo.InvariantCulture.NumberFormat ,(“BattingAverage&gt; = {0} AND BattingAverage&lt; = {1}” ,最小,最大);
if (textBox2.Text == "") view.RowFilter = string.Empty;
if (textBox3.Text == "") view.RowFilter = string.Empty;
}