WPF Datagrid Get Selected Cell Value

前端 未结 12 2070
遇见更好的自我
遇见更好的自我 2020-11-30 08:47

I want to get value for selected cell in datagrid , please anyone tell how to do this. i used SelectedCell changed event , how can i do that?

dataGrid1.Curre         


        
12条回答
  •  爱一瞬间的悲伤
    2020-11-30 09:33

    These are 2 methods that can be used to take a value from the selected row

        /// 
        /// Take a value from a the selected row of a DataGrid
        /// ATTENTION : The column's index is absolute : if the DataGrid is reorganized by the user,
        /// the index must change
        /// 
        /// The DataGrid where we take the value
        /// The value's line index
        /// The value contained in the selected line or an empty string if nothing is selected
        public static string getDataGridValueAt(DataGrid dGrid, int columnIndex)
        {
            if (dGrid.SelectedItem == null)
                return "";
            string str = dGrid.SelectedItem.ToString(); // Take the selected line
            str = str.Replace("}", "").Trim().Replace("{", "").Trim(); // Delete useless characters
            if (columnIndex < 0 || columnIndex >= str.Split(',').Length) // case where the index can't be used 
                return "";
            str = str.Split(',')[columnIndex].Trim();
            str = str.Split('=')[1].Trim();
            return str;
        }
    
        /// 
        /// Take a value from a the selected row of a DataGrid
        /// 
        /// The DataGrid where we take the value.
        /// The column's name of the searched value. Be careful, the parameter must be the same as the shown on the dataGrid
        /// The value contained in the selected line or an empty string if nothing is selected or if the column doesn't exist
        public static string getDataGridValueAt(DataGrid dGrid, string columnName)
        {
            if (dGrid.SelectedItem == null)
                return "";
            for (int i = 0; i < columnName.Length; i++)
                if (columnName.ElementAt(i) == '_')
                {
                    columnName = columnName.Insert(i, "_");
                    i++;
                }
            string str = dGrid.SelectedItem.ToString(); // Get the selected Line
            str = str.Replace("}", "").Trim().Replace("{", "").Trim(); // Remove useless characters
            for (int i = 0; i < str.Split(',').Length; i++)
                if (str.Split(',')[i].Trim().Split('=')[0].Trim() == columnName) // Check if the searched column exists in the dataGrid.
                    return str.Split(',')[i].Trim().Split('=')[1].Trim();
            return str;
        }
    

提交回复
热议问题