bind radiogroup with different data in every row b

2019-08-16 15:40发布

问题:

i added gridcontrol with two columns , Column 1 represent string and bind from datatable and another column represent radiogroupitem but i want to add different radiobutton value in every row based on question like in first row add ( Fine - Bad ) and next row add ( here - not here ) and last row add ( not yet - yes - tonight )

//bind question column
DataTable dtt = new DataTable();

dtt.Columns.Add("ID", typeof(string));

dtt.Rows.Add("How are you ?");
dtt.Rows.Add("Where are you ?");
dtt.Rows.Add("are you sleepy ?");

gridControl1.DataSource = dtt;

gridControl1.ForceInitialize();

// Bind radiobuttonitem
DataTable dataSource = new DataTable();
dataSource.Columns.Add("TypeID", typeof(int));
dataSource.Columns.Add("TypeName", typeof(string));

dataSource.Rows.Add(new object[] { 1, "A" });
dataSource.Rows.Add(new object[] { 2, "B" });
dataSource.Rows.Add(new object[] { 3, "C" });

foreach (DataRow dr in dataSource.Rows)
   repositoryItemRadioGroup1.Items
        .Add(new DevExpress.XtraEditors.Controls.RadioGroupItem(dr["TypeID"], dr["TypeName"].ToString()));

https://imgur.com/a/25Ofu

回答1:

Use the CustomRowCellEdit event to assign different editors to individual cells. You can store questions and RepositoryItemRadioGroups in a dictionary:

Dictionary<string, RepositoryItemRadioGroup> repositories = new Dictionary<string, RepositoryItemRadioGroup>();

RepositoryItemRadioGroup group1 = new RepositoryItemRadioGroup();
group1.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem("Fine", "Fine"));
group1.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem("Bad", "Bad"));
repositories.Add("How are you?", group1);

RepositoryItemRadioGroup group2 = new RepositoryItemRadioGroup();
group2.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem("Here", "Here"));
group2.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem("There", "There"));
repositories.Add("Where are you?", group2);

In the CustomRowCellEdit event handler, call the GetRowCellValue method to get the question, obtain the corresponding repository item from the dictionary and set the e.RepositoryItem parameter:

void GridView1_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e) {
    GridView view = sender as GridView;
    if (e.Column.FieldName == "Answer" && view.IsValidRowHandle(e.RowHandle)) {
        string question = (string)view.GetRowCellValue(e.RowHandle, "Question");
        RepositoryItemRadioGroup item;
        if(repositories.TryGetValue(question, out item))
            e.RepositoryItem = item;
    }
}

See also: Modify and Validate Cell Values