簡體   English   中英

datagrid在wpf c#中獲取選定的行和單元格值

[英]datagrid get selected rows and cells values in wpf c#

我想在wpf上重做舊的Windows窗體應用程序的代碼,並且在引用datagridview時遇到問題。

這是我的舊應用程序的空白外觀:

private void button2_Click(object sender, EventArgs e)
    {
        if (DGV1.Rows.Count > 0 && DGV1.SelectedRows != null)
        {
            bool wart = true;
            for (int i = 0; i < listBox2.Items.Count; i++)
            {
                listBox2.SelectedIndex = i;
                int w1 = Int32.Parse(listBox2.SelectedItem.ToString());
                int w2 = Int32.Parse(DGV1.SelectedRows[0].Cells[0].Value.ToString());

                if (w1 == w2)
                {
                    wart = false;
                    break;
                }
            }
            if (wart)
            {
                listBox2.Items.Add(DGV1.SelectedRows[0].Cells[0].Value);
            }
        }
    }

這是我的新應用程序的空白外觀:

private void Button1_Click(object sender, RoutedEventArgs e)
    {
        IList rows = dataGrid1.SelectedItems;

        if(dataGrid1.SelectedItem != null)
        {
            bool wart = true;


            for (int i =0; i < listBox1.Items.Count; i++)
            {
                listBox1.SelectedIndex = i;
                object item = dataGrid1.SelectedItem;

                int w1 = Int32.Parse(listBox1.SelectedItem.ToString());
                int w2 = Int32.Parse(dataGrid1.SelectedCells[0].Column.GetCellContent(item).ToString()); <--- !!

                if(w1 == w2)
                {
                    wart = false;
                    break;
                }
            }

            if(wart)
            {
                listBox1.Items.Add(dataGrid1.SelectedCells[0]); <-- !!
            }
        }
    }

如果該應用程序顯示在以下位置,則會在第二個位置溢出: 在此處輸入圖片說明

應該是: 在此處輸入圖片說明

請幫忙 :-)

可能應該是這樣的:

listBox1.Items.Add(dataGrid1.CurrentRow.Cells[0].Value);

這段代碼來自WinForms,但是我假設wpf的編碼可能沒有什么不同,因為兩者都在c#中。

dataGrid1.SelectedItem不僅僅是一些object ,它還具有具體的類型和屬性,例如IdTytulKategorieText

您需要對具體的類型和訪問屬性進行強制轉換,而不是嘗試從DataGridCellInfo等低級UI元素獲取值:

var item = (MyConcreteClass)dataGrid1.SelectedItem;
int w2 = item.Id;

暫無
暫無

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

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