Silverlight Datagrid get cell value - silverlight

I cant read cell text in datagrid. how can i do that? code and print screan on the image
thanks a lot
http://e1203.hizliresim.com/v/x/3x3dg.jpg code
http://e1203.hizliresim.com/v/x/3x3dw.jpg printscrean
here is the where i am creating grid; I think problem is ; I have two tables hr_Employee and hr_Scoring. when I bind "dayscore" from table hr_Scoring there is something wrong.
DomainServiceDB db = new DomainServiceDB();
//LoadOperation<hr_Employee> employeeLoadOp;
readonly Error err = new Error("Kaydederken hata oluştu. Lütfen tekrar deneyiniz.");
public PersonelUserControl()
{
InitializeComponent();
dgPersonelTakip.ItemsSource = db.hr_Employees;
db.Load(db.GetHr_EmployeeQuery());
int year = DateTime.Now.Year;
int month = DateTime.Now.Month;
int day = DateTime.DaysInMonth(year, month);
DataGridTextColumn adi = new DataGridTextColumn() { Header = "Adı ", Binding = new Binding("Name"), IsReadOnly = true };
DataGridTextColumn soyadi = new DataGridTextColumn() { Header = "Soyadı ", Binding = new Binding("Surname"), IsReadOnly = true };
dgPersonelTakip.Columns.Add(adi);
dgPersonelTakip.Columns.Add(soyadi);
for (int i = 1; i <= day; i++)
{
DataGridTextColumn c = new DataGridTextColumn()
{
IsReadOnly = false,
Header = i.ToString(),
// Binding = new Binding(path: "hr_Scorings.DayScore")
Binding = new Binding("hr_Scorings.DayScore")
};
dgPersonelTakip.Columns.Add(c);
}
}

Related

get cell content of WPF DataGrid after CellEditEnding and format numbers in DataGrid

Now I've searched for hours but didn't find an answer.
I have a WPF app with a DataGrid and want to edit data directly within a DataGrid cell. I can read the Data before change but not after change and therefore I can't save the changes.
And the second question is, how can I format numbers ("0.0") in a DataGrid column?
What I have so far:
There's nothing special in the XAML, only the raw definition of the DataGrid, without column definitions or something else.
And this is my source:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (!System.IO.File.Exists(dbFile[0]) | !System.IO.File.Exists(dbFile[1])) // the 2 XML data files
{
SystemSounds.Beep.Play();
MessageBox.Show("File(s)" + Environment.NewLine + " " + dbFile[0] + Environment.NewLine + "and/or" + Environment.NewLine + " " + dbFile[1] + Environment.NewLine + "don't exist." + Environment.NewLine + "The program will be closed.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
Environment.Exit(0);
}
OpenData();
}
private void OpenData()
{
DataTable dbDataTbl = new DataTable("MyData"); // name must be the same as in XML!!!
dbDataTbl.ReadXmlSchema(dbFile[1]);
dbDataTbl.ReadXml(dbFile[0]);
// DataGrid
DataView dataView = new DataView(dbDataTbl);
DataGrid1.ItemsSource = dataView;
// format column ID
DataGrid1.Columns[0].IsReadOnly = true; // ID
Style style = new Style(); // creates object of style class
style.TargetType = typeof(DataGridCell); // sets target type as DataGrid cell
Setter s = new Setter(); // create objects of setter class
s.Property = HorizontalAlignmentProperty;
s.Value = HorizontalAlignment.Right;
style.Setters.Add(s);
s = new Setter();
s.Property = ForegroundProperty;
s.Value = Brushes.LightGray;
style.Setters.Add(s);
DataGrid1.Columns[0].CellStyle = style;
// format column Date
style = new Style();
style.TargetType = typeof(DataGridCell);
s = new Setter();
s.Property = ContentStringFormatProperty;
s.Value = "yyyy-MM-dd"; // DOES NOT WORK !!!
style.Setters.Add(s);
DataGrid1.Columns[1].CellStyle = style;
// format column Weight
style = new Style();
style.TargetType = typeof(DataGridCell);
s = new Setter();
s.Property = HorizontalAlignmentProperty;
s.Value = HorizontalAlignment.Right;
style.Setters.Add(s);
s = new Setter();
s.Property = ContentStringFormatProperty;
//s.Value = "{}{0:0.0}"; // DOES NOT WORK !!!
s.Value = "0.0"; // DOES NOT WORK !!!
style.Setters.Add(s);
DataGrid1.Columns[2].CellStyle = style;
// format column Text
DataGrid1.Columns[3].MinWidth = 115;
}
private void DataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
int row = DataGrid1.Items.IndexOf(DataGrid1.CurrentItem);
int col = DataGrid1.CurrentCell.Column.DisplayIndex;
DataRowView drv = (DataRowView)DataGrid1.SelectedItem;
int id = Convert.ToInt32(drv.Row[0]); // value of ID
string val = drv.Row.ItemArray[col].ToString(); // old value of a cell
if (e.EditAction == DataGridEditAction.Commit)
{
var t = e.EditingElement as TextBox; // assumes columns are all TextBoxes
var txt = t.Text.ToString();
// when I press Enter after editing cell data I always get the old data,
// never the edited new one
// save data
// ...
}
}
thanks

ImageComboBoxEdit selected value not settable

I'm trying to add an ImageComboBoxEdit control onto a UserControl within my WinForms application.
public ShortCutUserControl()
{
var imageCollection = new ImageCollection { ImageSize = new Size(48, 48) };
imageCollection.Images.Add(Image.FromFile(#"Keyboard\ctrl.ico"));
imageCollection.Images.Add(Image.FromFile(#"Keyboard\alt.ico"));
functionKeyImageComboBoxEdit.Properties.LargeImages = imageCollection;
ImageComboBoxItem ctrlItem = new ImageComboBoxItem
{
Description = "Ctrl",
ImageIndex = 0
};
ImageComboBoxItem altItem = new ImageComboBoxItem
{
Description = "Alt",
ImageIndex = 1
};
functionKeyImageComboBoxEdit.Properties.Items.Add(altItem);
functionKeyImageComboBoxEdit.Properties.Items.Add(ctrlItem);
}
When the control is loaded:
I can't change the currently either directly through code or in the UI.
functionKeyImageComboBoxEdit.SelectedIndex = 0;
I've tried attaching events to the functionKeyImageComboBoxEdit, but none of these seem to be fired/captured;
functionKeyImageComboBoxEdit.SelectedIndexChanged += FunctionKeyImageComboBoxEditOnSelectedIndexChanged;
private void FunctionKeyImageComboBoxEditOnSelectedIndexChanged(object sender, EventArgs eventArgs)
{
//throw new NotImplementedException();
}
What am I missing from my code? I've been looking at the DevExpress ImageComboBoxEdit Documentation but can't see any problem.
The cause of the issue is that you don't set values for ImageComboBoxItems. Do this like:
ImageComboBoxItem ctrlItem = new ImageComboBoxItem
{
Description = "Ctrl",
ImageIndex = 0,
Value = "Ctrl"
};
ImageComboBoxItem altItem = new ImageComboBoxItem
{
Description = "Alt",
ImageIndex = 1,
Value = "Alt"
};

DataGrid CheckBox can't be checked

I got a problem with datagrid and DataGridCheckBoxClumn. First of all im creating struct for datagrid items:
public struct taxRateFromDatabase
{
public int rate { get; set; }
public string mark { get; set; }
public CheckBox c { get; set; }
}
And after that in my class adding columns, bindings etc:
StackPanel tSp = new StackPanel();
DataGrid taxRateDataGrid = new DataGrid();
DataGridTextColumn col0 = new DataGridTextColumn();
DataGridTextColumn col1 = new DataGridTextColumn();
DataGridCheckBoxColumn col2 = new DataGridCheckBoxColumn();
Binding b = new Binding("checkBox");
b.Mode = BindingMode.TwoWay;
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
taxRateDataGrid.Columns.Add(col0);
taxRateDataGrid.Columns.Add(col1);
taxRateDataGrid.Columns.Add(col2);
col0.Binding = new Binding("rate");
col1.Binding = new Binding("mark");
col2.Binding = b;
CheckBox c = new CheckBox();
c.Content = "a";
col0.Header = "Stawka";
col1.Header = "Oznaczenie";
col2.Header = "Status";
taxRateDataGrid.Items.Add(new taxRateFromDatabase { rate = 0, mark = "E", c = c });
taxRateDataGrid.Items.Add(new taxRateFromDatabase { rate = 1, mark = "G", c = c });
Problem is that I cant really check/uncheck that checkbox i have just added.
I have tried also without checkbox in struct definition (just empty datagridcheckboxcolumn), but that also doesnt work. Im creating it in class which will return datagrid so i cant really acces xaml.
Any sugestions will be appreciated ;)
I suggest you to use class instead struct (take a look here) and implement INotifyPropertyChanged interface in order to get the binding working.
Something like
public class TaxRateFromDatabase : INotifyPropertyChanged
{
private int _rate;
public int Rate
{
get { return _rate; }
set { _rate = value; OnPropertyChanged("Rate"); }
}
private string _mark;
public string Mark
{
get { return _mark; }
set { _mark = value; OnPropertyChanged("Mark"); }
}
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set { _isChecked = value; OnPropertyChanged("IsChecked"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
and for example
DataGrid taxRateDataGrid = new DataGrid();
DataGridTextColumn col0 = new DataGridTextColumn();
DataGridTextColumn col1 = new DataGridTextColumn();
DataGridCheckBoxColumn col2 = new DataGridCheckBoxColumn();
taxRateDataGrid.Columns.Add(col0);
taxRateDataGrid.Columns.Add(col1);
taxRateDataGrid.Columns.Add(col2);
col0.Binding = new Binding("Rate");
col1.Binding = new Binding("Mark");
col2.Binding = new Binding("IsChecked");
col0.Header = "Stawka";
col1.Header = "Oznaczenie";
col2.Header = "Status";
List<TaxRateFromDatabase> list = new List<TaxRateFromDatabase>();
list.Add(new TaxRateFromDatabase { Rate = 1, Mark = "E", IsChecked = true });
list.Add(new TaxRateFromDatabase { Rate = 23, Mark = "F", IsChecked = false });
taxRateDataGrid.ItemsSource = list;

dynamic button event in xml parsing

i create a dynamic button(xmlparsingbuildbutton) during a buttonclick(xmlparsingbutton) event.
I did a xml parsing...once each xml target is parsed, they will create an individual checkbox. What i need is this: Create a dynamic button event(xmlparsingbuildbutton). During this dynamic button event, for every checkbox that is checked, they will append a text file by writing new lines into the text file. This gets confusing to me because right now i have a foreachloop embedded in the xmlparsingbutton event that creates all these checkboxes.
Right now, I've coded it in such a way that whenever i check the checkboxes, my append of file event will not fire therefore I created this "xmlparsingbuildbutton" to help fire the event.From my understanding, usually i would hard code buttonclickevent, however in this case the target value always change in the foreach loop and therefore it is not right to just merely hardcode the buttonclickevent.
So my question is how do i have this button event to be inside the foreach loop of the xmlparsing event button? Please clarify my doubts. Many thanks!
Here is my code:
private void xmlparsingButton_Click(object sender, RoutedEventArgs e)
{
XDocument xmlDoc = XDocument.Load(#"C:\Build.xml");
var abc = from target in xmlDoc.Descendants("target")
select (string)target.Attribute("if");
ColumnDefinition gridCol1 = new ColumnDefinition();
gridCol1.Width = new GridLength(300);
ColumnDefinition gridCol2 = new ColumnDefinition();
gridCol2.Width = new GridLength(300);
ColumnDefinition gridCol3 = new ColumnDefinition();
gridCol3.Width = new GridLength(300);
ColumnDefinition gridCol4 = new ColumnDefinition();
gridCol4.Width = new GridLength(300);
tab4grid.ColumnDefinitions.Add(gridCol1);
tab4grid.ColumnDefinitions.Add(gridCol2);
tab4grid.ColumnDefinitions.Add(gridCol3);
tab4grid.ColumnDefinitions.Add(gridCol4);
RowDefinition gridRow1 = new RowDefinition();
gridRow1.Height = new GridLength(50);
RowDefinition gridRow2 = new RowDefinition();
gridRow2.Height = new GridLength(50);
RowDefinition gridRow3 = new RowDefinition();
gridRow3.Height = new GridLength(50);
RowDefinition gridRow4 = new RowDefinition();
gridRow4.Height = new GridLength(50);
RowDefinition gridRow5 = new RowDefinition();
gridRow5.Height = new GridLength(50);
RowDefinition gridRow6 = new RowDefinition();
gridRow6.Height = new GridLength(50);
RowDefinition gridRow7 = new RowDefinition();
gridRow7.Height = new GridLength(50);
RowDefinition gridRow8 = new RowDefinition();
gridRow8.Height = new GridLength(50);
RowDefinition gridRow9 = new RowDefinition();
gridRow9.Height = new GridLength(50);
RowDefinition gridRow10 = new RowDefinition();
gridRow10.Height = new GridLength(50);
RowDefinition gridRow11 = new RowDefinition();
gridRow11.Height = new GridLength(50);
RowDefinition gridRow12 = new RowDefinition();
gridRow12.Height = new GridLength(50);
tab4grid.RowDefinitions.Add(gridRow1);
tab4grid.RowDefinitions.Add(gridRow2);
tab4grid.RowDefinitions.Add(gridRow3);
tab4grid.RowDefinitions.Add(gridRow4);
tab4grid.RowDefinitions.Add(gridRow5);
tab4grid.RowDefinitions.Add(gridRow6);
tab4grid.RowDefinitions.Add(gridRow7);
tab4grid.RowDefinitions.Add(gridRow8);
tab4grid.RowDefinitions.Add(gridRow9);
tab4grid.RowDefinitions.Add(gridRow10);
tab4grid.RowDefinitions.Add(gridRow11);
tab4grid.RowDefinitions.Add(gridRow12);
int i = 0;
int j = 1;
System.Windows.Controls.Button XmlparsingbuildButton = new System.Windows.Controls.Button();
Grid.SetColumn(XmlparsingbuildButton, 4);
Grid.SetRow(XmlparsingbuildButton, 12);
XmlparsingbuildButton.Height = 23;
XmlparsingbuildButton.Width = 51;
XmlparsingbuildButton.Content = "Build";
tab4grid.Children.Add(XmlparsingbuildButton);
foreach(string target in abc)
{
if (target != null && !Dictionarycheck.ContainsKey(target))
{
System.Windows.Controls.CheckBox chk = new System.Windows.Controls.CheckBox();
chk.Name = target+"CheckBox";
chk.Content = target;
Grid.SetColumn(chk, i); //sets column
Grid.SetRow(chk, j); //sets row
tab4grid.Children.Add(chk); //adds the control
Tabitem5.Visibility = Visibility.Visible;
i++;
if (i == 4)
{
j++;
i = 0;
}
if (chk.IsChecked == true)
{
using (var writer = File.AppendText(#"c:\testing.txt"))
{
writer.WriteLine(target);
}
}
}
}
Tabitem5.Visibility = Visibility.Visible;
Tabcontrol1.SelectedIndex = 4;
}
I have to admit, I have problems understanding your problem. If I get it right, you're trying to do the following:
Parse a Xml document ("C:\Build.xml") with (roughly) this format:
targets>
target if="aaa" />
target if="bbb" />
/targets>
Create a CheckBox for each target tag with if- attribute set
Check the CheckBox containing the string you want to use
Click a button to append the checked strings to a text file ("c:\testing.txt")
If this is correct, then I think your solution won't do that. I not sure if I can understand what you are trying to do in your code. The way you set up the comboboxes they will never be checked the time you use your writer.
How about this:
Use a StackPanel (stackPanel1) instead of a grid. That way you don't have to create all the row definitions. (Ok, I have to admit, I don't know what all these columns are for)
Create a simple logic for a button to append the checked ComboBoxes to the file
code:
private void xmlparsingButton_Click(object sender, RoutedEventArgs e)
{
stackPanel1.Children.Clear();
XDocument xmlDoc = XDocument.Load(#"C:\Build.xml");
var abc = from target in xmlDoc.Descendants("target")
select (string) target.Attribute("if");
foreach (string target in abc)
{
if (target != null)
{
System.Windows.Controls.CheckBox chk = new System.Windows.Controls.CheckBox();
chk.Name = target + "CheckBox";
chk.Content = target;
chk.Tag = target;
stackPanel1.Children.Add(chk);
}
}
}
private void btnAppendToTextFile_Click(object sender, RoutedEventArgs e)
{
using (var writer = File.AppendText(#"c:\testing.txt"))
{
foreach (var child in stackPanel1.Children)
{
if ((child is CheckBox) && ((CheckBox) child).IsChecked.Value)
{
writer.WriteLine(((CheckBox)child).Tag);
}
}
}
}
I hope this helps you with your problem.

wpf toolkit datagrid performance

i am porting my application from windows forms to WPF. I have found that datagrid is available only through the WPF Toolkit. However i have some issues with performance. This could be because something that performed alright in windows forms does not in wpf since it has to be implemented differently. Anyhow, i am doing something like this:
// XAML
<toolkit:DataGrid x:Name="dataGrid" ItemsSource="{Binding Path=.}"/>
// C#
DataTable dataTable = new DataTable();
MyViewModel viewModel = new MyViewModel();
this.dataGrid.AutoGenerateColumns = false;
this.dataGrid.CanUserAddRows = false;
this.dataGrid.CanUserDeleteRows = false;
this.dataGrid.CanUserReorderColumns = true;
this.dataGrid.CanUserResizeColumns = true;
this.dataGrid.CanUserResizeRows = false;
this.dataGrid.CanUserSortColumns = true;
this.dataGrid.IsReadOnly = true;
this.dataGrid.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
this.dataGrid.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
this.dataGrid.ColumnHeaderHeight = 18;
this.dataGrid.RowHeight = 18;
this.dataGrid.DataContext = vm.dataGrid;
List<string> s = new List<string>();
for (int i = 0; i < 80; ++i)
{
s.Add("col" + i);
}
for (int i = 0; i < s.Count; ++i)
{
dataTable.Columns.Add(new DataColumn(s[i], typeof(string)));
Binding items = new Binding();
PropertyPath path = new PropertyPath(dataTable.Columns[i].ColumnName);
items.Path = path;
DataGridColumn dc = new DataGridTextColumn()
{
Header = dataTable.Columns[i].ColumnName,
Width=70,
Binding = items
};
this.dataGrid.Columns.Add(dc);
}
viewModel.dataGrid = dataTable;
this.dataGrid.DataContext = viewModel.dataGrid;
for (int i = 0; i < 1000; ++i)
{
var row = dataTable.NewRow();
for (int j = 0; j < s.Count; ++j)
{
row[s[j]] = "text" + s[j] + j;
}
dataTable.Rows.Add(row);
}
The above is a sample of simply generating same number of columns by binding each header.
When this loads, i get all the elements displayed correctly, but scrolling is really slow. I know that someone might say that i am rendering 80 columns and 1000 elements, but i had more than 10000 displayed in my windows forms application and had no issues with it.
The only difference with Windows Forms is that instead of using Binding i was setting the dataGridView's dataSource to the DataTable each time i was updating it.
Any ideas? What am i doing wrong?
Try setting EnableRowVirtualization=True

Resources