How to replicate/achieve Text='<% #Bind("field") %>' by only using code behind? (asp.net C#)

427 views Asked by At

I am creating a custom control which takes in a filepath (string) to an xml file and a dictionary of column headers, column fields and creates a gridview dynamically with CRUD operations. What I want to know is how to replicate/achieve Text='<% #Bind("field") %>' by only using code behind?

I was thinking of trying:

Dictionary<string, string> columns = new Dictionary<string, string>();

foreach (KeyValuePair<string, string> column in columns)
            {
                BoundField bField = new BoundField();
                bField.DataField = column.Value;
                bField.HeaderText = column.Key;
                GridView1.Columns.Add(bField);
            }

I'm open to suggestions as to either using .DataField or Text='<% #Bind("field") %>' or any way I haven't thought of if it achieves the end goal. As with the CRUD, can anyone recommend a good way to do this? Maybe dynamically inserting textbox and label controls into the gridview? I am using Visual Studio Express 2013 for Web.

1

There are 1 answers

3
sh1rts On BEST ANSWER

You override the ItemDataBound event. If you're thinking about dynamically adding controls to each row, you're better off using a different kind of templated control such as a Repeater.

UPDATE - an example

First make sure you handle the RowDataBound event (not ItemDataBound my bad, that's for the DataGrid): -

    protected override void OnInit(EventArgs e)
    {
        grid.RowDataBound += grid_RowDataBound;

Set up your columns from your dictionary of column names (I've used a string array, but you get the idea): -

        var columns = new string[] { "Column 1", "Column 2", "Column 3" };

        foreach (var columnName in columns)
        {
            grid.Columns.Add(new BoundField { HeaderText = columnName });
        }

Then in the RowDataBound event: -

    void grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var data = ({your object type})e.Row.DataItem;

            e.Row.Cells[0].Text = data.{fieldname};
            e.Row.Cells[1].Text = data.{fieldname};
            .
            .
            .
            e.Row.Cells[n].Text = {something};
        }
    }