检查组合框的状态并只读更改文本框

时间:2014-02-17 23:18:08

标签: c# winforms datagridview combobox

我有一个显示数据网格视图,文本框和组合框的表单。在组合框中选择列名称,并在文本框中键入搜索时,它会过滤并显示搜索到的数据。 如何检测组合框是否未选择任何内容,并将文本框readonly状态更改为true,选择某些内容后,将其更改为false以便我可以搜索?

DataTable dt;
        private void searchForm_Load(object sender, EventArgs e)
        {
            SqlCeConnection con = new SqlCeConnection(@"Data Source=|DataDirectory|\LWADataBase.sdf;");
            SqlCeDataAdapter sda = new SqlCeDataAdapter("select * from customersTBL", con);
            dt = new DataTable();
            sda.Fill(dt);
            dataGridView1.DataSource = dt;
            comboSearch.Items.Add("[First Name]");
                comboSearch.Items.Add("Surename");
            comboSearch.Items.Add("[Address Line 1]");
            comboSearch.Items.Add("[Address Line 2]");
            comboSearch.Items.Add("County");
            comboSearch.Items.Add("[Post Code]");
            comboSearch.Items.Add("[Contact Number]");
            comboSearch.Items.Add("[Email Address]");



        }



        private void searchTxt_TextChanged(object sender, EventArgs e)
        {


            {
                DataView dv = new DataView(dt);
                dv.RowFilter = "" + comboSearch.Text.Trim() + "like '%" + searchTxt.Text.Trim() + "%'";
                dataGridView1.DataSource = dv;
            }



        }

4 个答案:

答案 0 :(得分:0)

我添加了一个SelectedIndexChanged事件:

private void comboSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            searchTxt.ReadOnly = false;
        }

并将TextChanged事件更改为:

private void searchTxt_TextChanged(object sender, EventArgs e)
        {
            if (comboSearch.SelectedItem == null)
            {
                searchTxt.ReadOnly = true;
                MessageBox.Show("Please select a search criteria");
            }



            else
            {
                searchTxt.ReadOnly = false;
                DataView dv = new DataView(dt);
                dv.RowFilter = "" + comboSearch.Text.Trim() + "like '%" + searchTxt.Text.Trim() + "%'";
                dataGridView1.DataSource = dv;
            }
        }

现在它的功能如何

答案 1 :(得分:0)

你可以试试这个

if( ComboBox.SelectedItem == null ) {
   // do something
TextBox.ReadOnly = true;       //Using the TextBox.ReadOnly property

}
else{
Textbox.ReadOnly=false;
}

希望它可以帮到你!

答案 2 :(得分:0)

在FormLoad中将一行添加到comboSearch控件中以获取空行。确保它与[名字]项目有关。

comboSearch.Items.Add(string.Empty);
comboSearch.Items.Add("[First Name]");

为comSeSearch for SelectedIndexChanged添加事件处理程序。在事件内部,设置searchTxt控件的ReadOnly属性。它可能看起来像这样:

private void comboSearch_SelectedIndexChanged(object sender, EventArgs e)
{
    searchTxt.ReadOnly = comboSearch.SelectedIndex != 0;
}

答案 3 :(得分:0)

将空项添加到组合框中,然后

if(comboSearch.SelectedItem =="")
{
searchTxt.ReadOnly = true;
}
else
{
searchTxt.ReadOnly = false;
}

执行代码后添加以下行:

comboSearch.SelectedIndex =0;

确保您的空项目是第一项。

豫ICP备18024241号-1