指数超出范围。我无法弄清楚原因

时间:2015-03-01 10:05:59

标签: c# winforms datagridview

我正在为我的Windows窗体应用程序创建搜索栏。我有DataGridViewTextBoxComboBox

我的课程中有这个代码:

Classes.dbConnect _db = new Classes.dbConnect();    

public void SearchPosition()
{
    if (_search.Equals("POSITION"))
    {
        _db._conn.Open();
        string com = "SELECT * FROM tbl_Candidates" + " WHERE ( Position LIKE @pos )";
        _db._com = new SqlCommand(com, _db._conn);
        _db._com.Parameters.AddWithValue("@pos", "%" + _position + "%");

        try
        {
            _db._da = new SqlDataAdapter();
            _db._da.SelectCommand = _db._com;
            DataTable _dt = new DataTable();
            _db._da.Fill(_dt);
            BindingSource bs = new BindingSource();
            bs.DataSource = _dt;
            _dg.DataSource = bs;
            _db._da.Update(_dt);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
                _db._conn.Close();
        }
    }
}

然后我的textbox = TxtSearch.Text

private void txtSearch_TextChanged(object sender, EventArgs e)
{
    Classes.Admin.Candidates.position = txtSearch.Text;
    cand.SearchPosition();
}

我有我的combobox = cboCategory;里面的项目是"位置"

private void cboCategory_SelectedIndexChanged(object sender, EventArgs e)
{
    Classes.Admin.Candidates.search = cboCategory.Text;
}

当我开始输入我的TxtSearch.Text时。每个字母都使用与TxtSearch.Text相同的值搜索数据库。

DataGridView仅显示与TextBox中的值相同的值。 但是当DataGridView已经为空时,我会继续收到错误。

  

指数超出范围。必须是非负数且小于集合的大小。参数名称:索引

1 个答案:

答案 0 :(得分:0)

我想说你可以尝试做一个try catch块,每当datagridview为空或null时,就抛出异常。这样,应用程序不会崩溃,用户会注意到发生了什么

相关问题