NemeZiz February 2016

C# WPF DataGridView set Values programmatically (.Rows[x].Cells[y].Value)

I am trying to port this WinForms code for a DataGrid to a WPF Application, I already tried several solutions, but nothing worked yet.

Code I want to port:

this.dataGridView1.Enabled = true;
            this.dataGridView1.RowCount = 0x12;
            for (int i = 0; i < 0x12; i++)
            {
                this.dataGridView1.Update();
                this.dataGridView1.Rows[i].Cells[0].Value = i;
                this.dataGridView1.Rows[i].Cells[1].Value = this.GetName(i);
            }

The solutions I already tried:

XAML:

<DataGrid Name="DataGridView1" ItemsSource="{Binding}" AutoGenerateColumns="False" Margin="176,70,409,92" SelectionChanged="DataGridView1_SelectionChanged" >
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding ClientID}" Header="#"/>
                <DataGridTextColumn Binding="{Binding ClientName}" Header="Client Name"/>
            </DataGrid.Columns>
        </DataGrid>

C#:

#1:
if (dataGridView1.RowCount == 1)
            {
                dataGridView1.Rows.Add(11);
            }

            for (uint i = 0; i < 12; i++)
            {
                dataGridView1[0, Convert.ToInt32(i)].Value = i;
                dataGridView1[1, Convert.ToInt32(i)].Value = ClientNames(i);
            }
        }

#2:
DataTable dt = new DataTable();
DataColumn column;

column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "S1";
dt.Columns.Add(column);

column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "S2";
dt.Columns.Add(column);


if (dt.Items.Count == 1)
            {
                dt.Rows.Add(11);
            }

            for (uint i = 0; i < 12; i++)
            {
                DataRow row = myDT.NewRow();
                row["S1"] = i.ToString();
                row["        

Answers


Василий Шапенко February 2016

You can write following:

public class DataGridViewModel
   {
      public string Id{get;set;}
      public string Value{get;set;
   }

...

  for (int i = 0; i < 0x12; i++)
            {
               this.Models.Add(new DataGridViewModel(){Id=i,Value=GetName(i)};
            }

In XAML:

   <DataGrid Name="DataGridView1" ItemsSource="{Binding Models}" AutoGenerateColumns="False" Margin="176,70,409,92" SelectionChanged="DataGridView1_SelectionChanged" >
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Id}" Header="#"/>
                <DataGridTextColumn Binding="{Binding Value}" Header="Client Name"/>
            </DataGrid.Columns>
        </DataGrid>

Do not forget to implement NotifyPropertyChanged if needed. If you need further explanations, feel free to ask, i have shown only basic idea in the code above.

Post Status

Asked in February 2016
Viewed 1,767 times
Voted 14
Answered 1 times

Search




Leave an answer