簡體   English   中英

在WPF c#中刷新Datagrid

[英]Refreshing Datagrid in WPF c#

我有這個項目,在其中我必須將文件添加到我的數據網格中,然后單擊它,就可以編輯或刪除已添加的文件。 這是我的表格的屏幕截圖示例

在此處輸入圖片說明

當我單擊添加時,文本框中的文件將被添加到數據網格中。 它確實起作用。

然后,當我單擊數據網格中的數據時,文件名將插入到我的文本框中,以便我可以對其進行編輯。 然后,當我單擊“編輯”時,網格必須刷新以顯示已編輯的文件。 與刪除相同。

問題是當我嘗試編輯或刪除文件並刷新網格時,顯示錯誤。

我確定文件已被編輯/刪除,但我沒有刷新網格,而是報錯。

在此處輸入圖片說明

這是刷新網格的代碼。 每當我單擊“添加/編輯/刪除”按鈕時,我都會調用此方法

 public void DisplaySourceFile()
    {

        try
        {
            if (CONN.State != ConnectionState.Open)
            {
                CONN.Open();
            }


            CMD = new SqlCommand("Select sf_id as [ID], sf_name as [FILES] from [Source_File] where s_id = @s_id", CONN);
            CMD.Parameters.AddWithValue("@s_id", SourceId);
            DA = new SqlDataAdapter(CMD);
            DT = new DataTable("Role");
            DA.Fill(DT);
            dataGridFile.ItemsSource = DT.DefaultView;

        }
        catch
        {
            throw;
        }
        finally
        {
            if (CONN.ToString() != String.Empty && CONN.State != ConnectionState.Closed)
                CONN.Close();
        }

    }

這是在我的數據網格中選擇項目時的代碼:

 private void dataGridFile_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        bo_source = new BO.BO_Source();
        dal_source = new DAL.DAL_Source();
        //Check if there is selected item

            dal_source.selectedSourceFile = Convert.ToInt32((DT.Rows[dataGridFile.SelectedIndex])[0].ToString());

        selectedSource = dal_source.selectedSourceFile;
        btnEdit.IsEnabled = true;
        btnDelete.IsEnabled = true;
        btnAdd.IsEnabled = false;

        if (dal_source.GetSourceFileInfo(bo_source) == true)
        {
            txtFileName.Text = bo_source.sf_name;
        }
    }

誰能幫我嗎。

從您共享的內容中可以看到,錯誤是指索引-1處的行。

由於任何索引都從0開始,因此-1不可能被編輯或刪除。

因此,此方案的解決方案是管理索引

  • 刪除第一行或最后一行時,它不應低於0
  • 刪除最后一行時也不應超過最大行數1

如果它跨越任何邊界,則需要相應地處理。

問題似乎在這里

//Check if there is selected item
dal_source.selectedSourceFile = Convert.ToInt32((DT.Rows[dataGridFile.SelectedIndex])[0].ToString());

所以也許改變它來驗證

//Check if there is selected item
int selectedIndex = dataGridFile.SelectedIndex;
if(selectedIndex > -1 && selectedIndex < DT.Rows.Count)
{
    dal_source.selectedSourceFile = Convert.ToInt32((DT.Rows[selectedIndex])[0].ToString());

    selectedSource = dal_source.selectedSourceFile;
    btnEdit.IsEnabled = true;
    btnDelete.IsEnabled = true;
    btnAdd.IsEnabled = false;

    if (dal_source.GetSourceFileInfo(bo_source) == true)
    {
        txtFileName.Text = bo_source.sf_name;
    }
}

這應該可以解決您當前的問題。

MVVM方式

這種方法將您的模型與數據網格綁定為ObservableCollection,然后操作集合而不是處理UI元素,因此刪除,添加或刷新將由WPF強大的綁定框架處理

暫無
暫無

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

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