Home > Software design >  How do I change specific Element names in a DataGrid column C#
How do I change specific Element names in a DataGrid column C#

Time:12-04

The datagrid is from a xml file

I would like to replace certain names from the "Name" column in the Datagrid. I don't need to alter the xml file from which the grid is populated , just the display names .

example "panel1" to "pressure1" and "checkBox5" to "Selected"

The source xml

<ChildForm>
  <Control Type="System.Windows.Forms.Panel" Name="panel1">
    <Visible>True</Visible>
    <Control Type="System.Windows.Forms.Button" Name="button11">
      <Visible>True</Visible>
    </Control>
    <Control Type="System.Windows.Forms.Button" Name="button10">
      <Visible>True</Visible>
    </Control>
  </Control>
  <Control Type="System.Windows.Forms.GroupBox" Name="groupBox5">
    <Visible>True</Visible>
    <Control Type="System.Windows.Forms.ComboBox" Name="cmbTBU">
      <Text>Unbalaced</Text>
      <Visible>True</Visible>
    </Control>
    <Control Type="System.Windows.Forms.Button" Name="button8">
      <Visible>True</Visible>
    </Control>
    <Control Type="System.Windows.Forms.Button" Name="button9">
      <Visible>False</Visible>
    </Control>
    <Control Type="System.Windows.Forms.TextBox" Name="shutoff">
      <Text>21</Text>
      <Visible>True</Visible>
    </Control>
    <Control Type="System.Windows.Forms.CheckBox" 

EDIT : The code that populates the grid

                DataSet dataSet = new DataSet();
                dataSet.ReadXml(dialog.FileName);
                dataGridView1.DataSource = dataSet.Tables[0];


                this.dataGridView1.Columns["Type"].Visible = false;
                this.dataGridView1.Sort(this.dataGridView1.Columns["Visible"], ListSortDirection.Descending);

CodePudding user response:

You'll need to enumerate the table after you read it, performing replacements:

var d = new Dictionary<string, string>(){
  { "panel1" ,"pressure1" },
  { "checkBox5", "Selected"}
};

foreach(DataRow r in dataSet.Tables[0].Rows){
  if(d.TryGetValue(r["Name"].ToString()], out string v))
    r["Name"] = v;  
}

This won't change the XML file but it will change what is displayed.

Note that it will change what is output if you save the dataset to an xml file again. If that is not supposed to happen, the easiest thing/way is to use a DataGridViewComboBox to decode the "panel1" to "pressure1". I can post an example of that if required

  • Related