Home > Software engineering >  How to add customized columns with values to a DataGrid that already contained data from database?
How to add customized columns with values to a DataGrid that already contained data from database?

Time:09-04

I'm learning to create a C# WPF Desktop Application. Currently I had retrieved the data from the database and paste it into the DataGrid.

                string sql = "SELECT scenarioName, scenarioDate FROM tbl_scenario";
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
                DataTable dtScenario = new DataTable();
                sqlDataAdapter.Fill(dtScenario);
                scenarioDataGrid.ItemsSource = dtScenario.DefaultView;

Then this is the xaml code I use to create the DataGrid.

                <DataGrid.Columns>
                    <DataGridTextColumn x:Name="scenarioNumberColumn" Binding="{Binding Path=scenarioID}" Header="No." Width="50" IsReadOnly="True"/>
                </DataGrid.Columns>
            </DataGrid>

Currently, this is what I got DataGrid Result. I wanted to add some numbers in the No. column as well but I failed to do so too.

My question is, are there any ways that I can add more columns with value in the DataGrid? I also want to add more columns on the right with items that are not from database. I tried many ways that I saw online but none of them do the tricks, or maybe I'm doing it wrong.

Thank you in advance.

CodePudding user response:

The best way might that comes to my mind would be to create a custom object with all the fields you wanttt to have in the DataGrid.

// I am not inspired for the name sorry...
internal class DataForDataGrid
{
    // Data from database
    public string? ScenarioName { get; set; }
    public DateTime? ScenarioDate { get; set; }

    // Data from Somewhere else
    public string? scenarioID{ get; set; }
}

Then you keep your sql query, but you fill a list of the custom object. Several ways to do it like using a DbReader object, an ORM (Dapper, EntityFramework)

IEnumerable<DataForDataGrid> dataForDatGridList = new List<DataForDataGrid>();

string sql = "SELECT scenarioName, scenarioDate FROM tbl_scenario";
SqlCommand cmd = new SqlCommand(sql, conn);

using (SqlDataReader dataReader = cmd .ExecuteReader()
{
    while (dataReader.Read())
    {
        dataForDatGridList .Add(new DataForDataGrid()
        {
            ScenarioName = dataReader.GetString(0),
            ScenarioDate = GetDateTime.GetString(1),
            scenarioID= "Data you need from somwhere else",
        });
    });
}

scenarioDataGrid.ItemsSource = dataForDatGridList;

Then in the xml

<DataGrid.Columns>
    <DataGridTextColumn 
            x:Name="scenarioNumberColumn"
            Binding="{Binding Path=scenarioID}"
            Header="No."
            Width="50"
            IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

If you have a couple of hours to invest, I recommend this youtube channel SingletonSean with tons of tutorials and explanations about WPF.

Hope it helps

CodePudding user response:

To add a new column, add this after the DataTable declaration:

DataColumn dc = new DataColumn();
dc.ColumnName = "new_column";
dtScenario.Columns.Add(dc);
//to access the column in selected rows:
dtScenario.Rows[0]["new_column"] = "test value";
  • Related