Get hidden value from wpf datagrid - c#

Can i get value Hidden column from DataGrid?
<DataGridTextColumn Header="" Width="10" Binding="{Binding id}" Visibility="Hidden"/>
Using this code, i get exception.
Data.IdServ = ((TextBlock)DataGridService.Columns[1].GetCellContent(row)).Text;
if (dgUserEnroll.SelectedItem != null)
{
var data = (User)dgUserEnroll.SelectedItem;
var userID = data.UserId;
}
this is a not option, because i have tableadapter when receiveng data

You can use your code behind too. You just need to hide the column in a different way:
<DataGridTextColumn Header="" MaxWidth="0" Binding="{Binding id}" />
i.e. remove the Visibility attribute and set MaxWidth to zero.

You have a Binding with id field, so use it instead of accessing cell content.

I found two ways
first
string ID = ((DataRowView)DataGridService.SelectedItem).Row["id"].ToString();
second
var data = (DataRowView)DataGridService.SelectedItem;
var userId = data.Row["id"];

First convert selected item of data grid view to ItemsSource of data grid view:
dataGridUser.ItemsSource is View_Users ==>
dataGridUser.ItemsSource = database.Database.SqlQuery<View_Users>(
"select * from view_users where 1=1"+searchString()).ToList();
Then, to get value Hidden or Visible column from DataGrid:
var id= ((View_Users)dataGridUser.SelectedItem).UserID;

I came with a simpler solution, suppose you have bound a List to the Datagrid, YourClass has Id property the XAML would look like :
<DataGrid x:Name="ListeUrls" AutoGenerateColumns="False" Margin="1,0,-1,27" >
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="MouseDoubleClick" Handler="DataGridCell_MouseDoubleClick"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Id}" Visibility="Hidden"></DataGridTextColumn>
<DataGridTextColumn Header="Vendor" Binding="{Binding Vendor}" Foreground="red" FontWeight="Bold" ></DataGridTextColumn>
<DataGridTextColumn Header="Url" Binding="{Binding url}" ></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
In the code behind :
Somewhere you have bound the ListeUrls:
ListeUrls.ItemsSource = new List{ .... };
private void DataGridCell_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var dataGridCellTarget = (DataGridCell)sender;
var parent = VisualTreeHelper.GetParent(dataGridCellTarget);
.....
}
You use the VisualTreeHelper to get the parent of the cell on which you triggered the mouse doubleclick. The parent has the properties of YourClass thus the Id.
I think no need to set the width of the hidden DataGridColumn, set its Visibility to Hidden is enough.

</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Delete">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="delete" Width="40" Click="Delete_Click" Background="#FFD80000">
<materialDesign:PackIcon Kind="Delete" Width="25" Margin="-10,0,0,0" FontWeight="Bold"></materialDesign:PackIcon>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Edit">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="edit" Width="40" Click="Edit_Click" Background="#FF673AB7">
<materialDesign:PackIcon Kind="Edit" Width="25" Margin="-10,0,0,0" FontWeight="Bold"></materialDesign:PackIcon>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!--<DataGridTextColumn Width="300" Binding="{Binding [2]}" Header="Price"></DataGridTextColumn>-->
</DataGrid.Columns>

Related

How do I clear specific columns in DataGrid?

i am using WPF, connected to SQL DataBase via LinqToSql.
I have filled DataGrid using ItemsSource.
I would like to clear everything in my DataGrid, except first two rows(ID,first and second name), and Headers ofcourse, by pressing a button. All items i would like to(either set to null or 0) remove, are floats, but I can't find the right logic to do that.
Here is the picture of my DataGrid-->
public partial class Spisak : Microsoft.Office.Interop.Excel.Window
{
DiplomskiDataContext diplomski = new DiplomskiDataContext();
public Spisak()
{
InitializeComponent();
dataGridRadnici.ItemsSource = diplomski.Radniks.ToList();
}
}
This is my code behind, and here is Xaml code:
<DataGrid HorizontalAlignment="Left" Name="dataGridRadnici" AutoGenerateColumns="False" Height="260" Margin="10,120,0,0" VerticalAlignment="Top" Width="550">
<DataGrid.Columns>
<DataGridTextColumn Header="Ime" Binding="{Binding Ime}"></DataGridTextColumn>
<DataGridTextColumn Header="Prezime" Binding="{Binding Prezime}"></DataGridTextColumn>
<DataGridTextColumn Header="BrSati" Binding="{Binding BrojSati, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
<DataGridTextColumn Header="Prekovremeni" Binding="{Binding BrojPrekovremenih, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
<DataGridTextColumn Header="Gorivo" Binding="{Binding BrojDana, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
<DataGridTextColumn Header="Bonus" Binding="{Binding Bonus}"></DataGridTextColumn>
<DataGridTextColumn Header="VracanjeDuga" Binding="{Binding VracanjeDuga}"></DataGridTextColumn>
<DataGridTextColumn Header="UkZarada" Binding="{Binding UkupnaPlata, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
<DataGridTextColumn Header="UkSaGorivom" Binding="{Binding UkupnoSaGorivom, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
</DataGrid.Columns>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Izmeni" Click="MenuItem_Click"></MenuItem>
<MenuItem Header="Obrisi" Click="MenuItem_Click_1"></MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
Change the type of the columns that you want to be able to blank out from float to Nullable<float> (float?) and simply set the properties to null:
var sourceList = dataGridRadnici.ItemsSource as List<Radnik>; //or whatever your data is called
foreach (var item in sourceList)
{
item.BrojPrekovremenih = null; // or 0
//set the other properties the same way...
}
You also need to implement the INotifyPropertyChanged interface and raise property change notifications in your data class.

WPF get TextBox Value from datagridtemplatecolumn

Hello guys I am trying to get TextBox Named "txtQty" value from DataGridTemplateColum
Here is the code, Hope someone Helps me....
.XML
<DataGrid x:Name="dataGridMain">
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}" IsReadOnly="True" Visibility="Hidden"/>
<DataGridTextColumn Header="Name" Binding="{Binding PName}" IsReadOnly="True"/>
<DataGridTemplateColumn Header="Qty" >
<DataGridTemplateColumn.CellTemplate >
<DataTemplate >
<StackPanel Orientation="Horizontal">
<TextBox x:Name="txtQty"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
I tried using this code
DataRowView dt = dataGridMain.SelectedItem as DataRowView;
String value = dt["Qty"].ToString());
After some struggle I found this solution helpful.....
int i=5; //Set this equal to desired column index....
ContentPresenter myCp = dataGridMain.Columns[i].GetCellContent(dataGridMain.SelectedItem) as ContentPresenter;
var myTemplate = myCp.ContentTemplate;
TextBox mytxtbox = myTemplate.FindName("txtQty", myCp) as TextBox;
MessageBox.Show(mytxtbox.Text);
My guess is that you are trying to access the selected row here is the answer for that https://stackoverflow.com/a/3913791/1449779 also don't forget to bind the text box as DonBoitnott comment

How to get data from combobox from datagrid in WPF?

I have been looking for a way to get data out from this datagrid combobox that i made. Specifically the selected value of every combobox from columns. I am new to WPF and would be really grateful if someone would help.
Thanks
XAML:
<DataGrid x:Name="tb" Margin="5,51,5,5" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridCheckBoxColumn Header="Include" Binding="{Binding Include}"/>
<DataGridTemplateColumn Header="Measure" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox Margin="2" ItemsSource="{Binding Measure}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
C#:
ObservableCollection<State> items = new ObservableCollection<State>();
foreach (string col in columns)
{
items.Add(new State()
{
Name = col,
Include = true,
Measure = new ObservableCollection<string>() { "Sum", "Average" }
});
}
DataContext = items;
Picture of the columns:
I think you're confusing stuff. I assume you want your State items to have a string Measure property, and not a collection of them, but you want to be able to select the Measure value from a Combo with several options...
If that's the case, then you should redefine your Measure property to be a single string, and not a collection.
ObservableCollection<State> items = new ObservableCollection<State>();
foreach (string col in columns)
{
items.Add(new State()
{
Name = col,
Include = true,
Measure = string.Empty // Initialize it to whatever you want
});
}
DataContext = items;
Then create the Measure values collection somewhere else in your DataContext, or if you don't have a DataContext other than your collection, you can define it in XAML.
And, finally, in your DataGrid you must bind both the ItemsSource and the SelectedItem properties of your Combos. They'll share the same ItemsSource, which must be fetched from wherever you put the collection, instead of the row's DataContext:
<DataGrid x:Name="tb" Margin="5,51,5,5" ItemsSource="{Binding}"
AutoGenerateColumns="False">
<DataGrid.Resources>
<!-- This is where the values are defined -->
<col:ArrayList x:Key="MeasureValues">
<sys:String>Sum</sys:String>
<sys:String>Average</sys:String>
</col:ArrayList>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridCheckBoxColumn Header="Include" Binding="{Binding Include}"/>
<DataGridTemplateColumn Header="Measure" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox Margin="2"
SelectedItem="{Binding Measure}"
ItemsSource="{StaticResource MeasureValues}" />
<!-- And this is where you consume those values -->
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
If you don't wanna put the values in XAML, you'll have to define the collection in another DataContext and create a Binding to it somehow (using RelativeSource, ElementName and stuff like that).
This works with a DataGridComboBoxColumn, too, of course:
<DataGrid x:Name="tb" Margin="5,51,5,5" ItemsSource="{Binding}"
AutoGenerateColumns="False">
<DataGrid.Resources>
<!-- This is where the values are defined -->
<col:ArrayList x:Key="MeasureValues">
<sys:String>Sum</sys:String>
<sys:String>Average</sys:String>
</col:ArrayList>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridCheckBoxColumn Header="Include" Binding="{Binding Include}"/>
<DataGridComboBoxColumn Header="Measure" Width="*"
SelectedItemBinding="{Binding Measure}"
ItemsSource="{StaticResource MeasureValues}" />
<!-- And this is where you consume those values -->
</DataGrid.Columns>
</DataGrid>

Data binding Datagrid WPF

I have created a datagrid with each object has their own line. I added two column (edit,remove) but the command won't execute. I am using MVVM pattern. Here is the datagrid
<DataGrid Name="dgBillMeta" ItemsSource="{Binding FileObjectCollection}" AutoGenerateColumns="False" Grid.Row="0" IsReadOnly="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding id}"></DataGridTextColumn>
<DataGridTextColumn Header="Name" Binding="{Binding attName}"></DataGridTextColumn>
<DataGridCheckBoxColumn Header="Key" Binding="{Binding isKey}"></DataGridCheckBoxColumn>
<DataGridTextColumn Header="Type" Binding="{Binding attType}"></DataGridTextColumn>
<DataGridTextColumn Header="Required" Binding="{Binding isRequired}"></DataGridTextColumn>
<DataGridTextColumn Header="Location" Binding="{Binding attLoc}"></DataGridTextColumn>
<DataGridTextColumn Header="Length" Binding="{Binding attLength}"></DataGridTextColumn>
<DataGridTextColumn Header="Decimal" Binding="{Binding isDecimal}"></DataGridTextColumn>
<DataGridTextColumn Header="Alignment" Binding="{Binding attAlignment}"></DataGridTextColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Edit"></Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="delete">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding remCommand}" Content="Remove"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
I can see edit, and remove but when clicking on it, the object does not execute from my ModelView. If I put the button outside the datagrid ( anywhere on the windows, it does work).
Here how the ViewModel works
internal class BillMetaDataViewModel
{
private ObservableCollection<BillMetaData> _MyDataList;
private Command removeCommand;
public BillMetaDataViewModel()
{
Database dbobj = new Database();
MongoDatabase dtbase = dbobj.getDatabase;
var collection = dtbase.GetCollection<BillMetaData>("BillMetaData");
var entity = collection.FindAll();
_MyDataList = new ObservableCollection<BillMetaData>(entity.ToList());
removeCommand = new Command(removeComm);
}
public ObservableCollection<BillMetaData> FileObjectCollection
{
get { return _MyDataList; }
}
public void removeComm()
{
MessageBox.Show("Hello MessageBox");
}
public Command remCommand
{
get { return removeCommand; }
}
}
I may be missing selection number, but i am trying to learn first I believe it has to do something with the path but i am not sure how it would work. I have defined my datacontext on the xaml as follow
InitializeComponent();
DataContext = new BillMetaDataViewModel();
The DataTemplate for the button doesn't set the DataContext for button, try the following
Set the Name of the DataGrid to x:Name and
<DataGrid x:Name="dgBillMeta" ItemsSource="{Binding FileObjectCollection}" AutoGenerateColumns="False" Grid.Row="0" IsReadOnly="False" >
use element name and set the correct binding path.
<DataGridTemplateColumn Header="delete">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding Path=DataContext.remCommand, ElementName=dgBillMeta}" Content="Remove"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Get SelectedItem value from DataGrid

I have a DataGrid in my WPF application as below.
<DataGrid Name="stDataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Edit" CanUserResize="False" Width="SizeToHeader">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button" Click="btnEdit_Click">
<StackPanel>
<Image Source="images/edit.png"/>
</StackPanel>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" IsReadOnly="True"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Path=Age}" Header="Age" IsReadOnly="True"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Path=Sex}" Header="Sex" IsReadOnly="True"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
Binding data into DataGrid like this.
using (var context = new CLASS_DBEntities())
{
var query = from s in context.STUDENT
orderby s.STUDENT_NAME
select new {s.STUDENT_ID, Name = s.STUDENT_NAME, Age = s.STUDENT_AGE,
Sex = s.STUDENT_SEX};
stDataGrid.ItemsSource = query.ToList();
}
When user click Button in DataGrid, I need to get STUDENT_ID value. How can i do this ?
Set an attached property of the same type as student_id on your button and bind it relativly to the datacontext.student_id of the DataGridRow control which should be the parent to all yours cells in a row.
Once you enter btnEdit_Click method just read out the value from your attached property.
Finally found answer by myself.
in btnEdit_Click method,
dynamic customerRow = stDataGrid.SelectedItem;
MessageBox.Show(customerRow.STUDENT_ID+"");

Categories

Resources