0

我试图只显示DataGridView输入的姓氏的行。从那里我可以构建我的程序的其余部分,但我遇到了减速带。我在网上看到了我的活动中的那段代码,但它不起作用。它在 else 括号处中断。有什么建议吗?对不起,我是新手,但如果我学过一次,我会永远记住。Submit_Button_Click

public partial class Form1 : Form
{
    string LastName;
    //string FirstName;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.aRMORERS_TableAdapter.Fill(this.armorersDataSet._ARMORERS_);
    }

    private void Submit_Button_Click(object sender, EventArgs e)
    {
        LastName = LastName_TextBox.Text;
        //FirstName = FirstName_TextBox.Text;
        for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
        {
            if (dataGridView1.Rows[i].Cells[0].Value.ToString() == LastName)
            {
                dataGridView1.Rows[i].Selected = true;
                dataGridView1.Rows[i].Visible = true;
            }
            else
            {
                dataGridView1.Rows[i].Visible = false;
                dataGridView1.Rows[i].Selected = false;
            }
        }
    }
}
4

1 回答 1

0

我建议您使用过滤而不是循环。

尝试Submit_Button_Click通过以下方式替换事件处理程序中的代码:

    private void Submit_Button_Click(object sender, EventArgs e)
    {
        string lastName = LastName_TextBox.Text;
        (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = 
             string.Format("Field_Name = '{0}'", lastName);
    }

其中“Field_Name”应替换为您的列名。

PS 如果您不需要姓氏的精确匹配,您可以使用带有通配符的 LIKE 运算符使用“包含”和“开始于”(或“结束于”)模式进行过滤。

包含文本框中的所有字符:string.Format("Field_Name LIKE '*{0}*'", lastName);

以文本框中的字符开头:string.Format("Field_Name LIKE '{0}*'", lastName);

以。。结束:string.Format("Field_Name LIKE '*{0}'", lastName);

于 2013-09-05T14:42:46.040 回答