【问题标题】:index was out of range. I can't figure out why指数超出范围。我不知道为什么
【发布时间】:2015-03-02 17:35:00
【问题描述】:

我正在为我的 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();
        }
    }
}

然后我有我的文本框 = TxtSearch.Text

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

我有我的组合框 = cboCategory;里面的项目是“位置”

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

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

DataGridView 仅显示与TextBox 中的值相同的值。 但是当DataGridView 已经为空时,我不断收到错误消息。

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

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    我会说你可以尝试做一个try catch 块,只要datagridview 为空或为空,你就会抛出一个异常。这样应用程序就不会崩溃,并且用户会注意到发生的事情

    【讨论】:

    • Pinto,谢谢.. 我有点知道如何尝试 catch,但我还是新手,我不知道当 datagridview 为空或 null 时如何处理异常..
    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2014-06-19
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    相关资源
    最近更新 更多