簡體   English   中英

在 FormLoad 時 DataGridView SelectionChanged 事件中拋出“索引超出范圍”異常

[英]"Index was out of range" Exception Thrown in DataGridView SelectionChanged event While FormLoad

我在FormLoad使用以下代碼填充了名為DataSourceGrid DataGridView

String mquery = "SELECT ProductName,UnitPrice,CategoryName FROM ProductsTable INNER JOIN CategoryTable ON ProductsTable.Categoryid = CategoryTable.Categoryid";
                using (SqlConnection con = new SqlConnection(conString))
                {
                    SqlDataAdapter sda = new SqlDataAdapter(mquery, con);
                    con.Open();
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    DataSourceGrid.DataSource = dt;

                }

我使用以下代碼在SelectionChanged事件塊中SelectionChanged DataGridView

                int curRow = -1;
                int curColumn = -1;
                curRow = DataSourceGrid.CurrentRow.Index;
                curColumn = DataSourceGrid.CurrentCell.ColumnIndex;
                string firstCellValue = DataSourceGrid.SelectedRows[curRow].Cells[curColumn].Value.ToString();
                if (DataSourceGrid.CurrentRow.Index >= -1)
                {
using (SqlConnection con = new SqlConnection(conString))
                    {

                        String query = "SELECT ProductName,UnitPrice,CategoryName FROM ProductsTable INNER JOIN CategoryTable ON ProductsTable.Categoryid = CategoryTable.Categoryid WHERE ProductName='" + firstCellValue + "'";
                        con.Open();
                        SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
                        sdr.Read();
                        ProductNameText.Text = sdr.GetValue(0).ToString();
                        UnitPriceText.Text = sdr.GetValue(1).ToString();
                        CategoryText.Text = sdr.GetValue(2).ToString();

                    }

當我單擊一行時,數據將顯示在相應的文本框中。 我的問題是當FormLoad拋出一個異常時,說Index was out of range...這是 Exact Exeption,感謝您的支持。

將您的代碼更改為:

                int curRow = DataSourceGrid.CurrentRow.Index;
                int curColumn = DataSourceGrid.CurrentCell.ColumnIndex;

                // First check for -1 and then do the rest.
                if (curRow > -1 && curColumn > -1)
                {
                    string firstCellValue = DataSourceGrid.SelectedRows[curRow].Cells[curColumn].Value.ToString();

數組的索引從0Length-1 ,所以如果索引是 -1 那么它就是異常所說的OutOfIndex

如果您想在值為 -1 時訪問第一個元素,則另一種解決方案如下。

if (curRow >= -1 && curColumn >= -1)
{
    curRow = curRow == -1 ? 0 : curRow;
    curColumn = curColumn == -1 ? 0 : curColumn;
    string firstCellValue = DataSourceGrid.SelectedRows[curRow].Cells[curColumn].Value.ToString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM