0

as a part of an exercise i'm attempting to do, its used for a parents meetings day, where i want to display a table of meetings, with a radio button next to the hour and so a student can login and embed himself to the time he wants.

so i have a table control which i build dynamically from the database MeetingsTable that has the columns:

  • meetingHour
  • meetingDate
  • meetingPlace
  • studentID

the code behind looks like this: (some of it is in hebrew so ignore it)

public string error = "";//Initialize error string
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        MultiView1.ActiveViewIndex = 0;
    }
    string fileName = "ParentsDayDB.accdb";
    string selectQuery = "SELECT * FROM Meetings";
    DataBindMeetingsTable(fileName, selectQuery);

}

protected void IDButton_Click(object sender, EventArgs e)
{
    string studentID = IDTextBox.Text;
    string pattern = @"^\d{9}$";
    Regex reg = new Regex(pattern);
    if (reg.IsMatch(studentID))
    {
        string fileName = "ParentsDayDB.accdb";
        string selectQuery = "SELECT * FROM Students WHERE studentID = '" + studentID + "'";
        if (MyAdoHelper.IsExist(fileName, selectQuery))
        {
            DataTable table = MyAdoHelper.ExecuteDataTable(fileName, selectQuery);
            string studentName = (string)table.Rows[0]["studentName"];
            string studentClass = (string)table.Rows[0]["studentClass"];
            string parentName = (string)table.Rows[0]["parentName"];
            Student student = new Student(studentID, studentClass, studentName, parentName);
            Session["student"] = student;
            if ((bool)table.Rows[0]["isAdmin"] == true)
            {
                Session["isAdmin"] = "true";
            }
            MultiView1.ActiveViewIndex = 1;
        }
        else
        {
            error = "<hr align=\"right\" width=\"230px\" /> תעדות הזהות לא קיימת";
        }
    }
    else
    {
        error = "<hr align=\"right\" width=\"440px\" /> אנא הכנס תעודת זהות תקינה בעלת 9 ספרות";
    }
}


public void DataBindMeetingsTable(string fileName, string selectQuery)
{

    DataTable dt = MyAdoHelper.ExecuteDataTable(fileName, selectQuery);
    //הוספת הכותרות
    TableRow tr = new TableRow();
    TableCell tc = new TableCell();
    tc.Text = "שעה";
    tr.Cells.Add(tc);
    tc = new TableCell();
    tc.Text = "תאריך";
    tr.Cells.Add(tc);
    tc = new TableCell();
    tc.Text = "מיקום";
    tr.Cells.Add(tc);
    tc = new TableCell();
    tc.Text = "ת.ז. תלמיד";
    tr.Cells.Add(tc);
    MeetingsTable.Rows.Add(tr);

    //הוספת הנתונים לטבלה
    int numCols = dt.Columns.Count;
    int radioIndex = 1;
    foreach (DataRow dr in dt.Rows)
    {
        tr = new TableRow();
        for (int i = 0; i < numCols; i++)
        {
            object item = dr.ItemArray[i];
            TableCell c = new TableCell();
            c.BorderWidth = 1;
            if (i == 0)//אם בתא צריך להיות כפתור של שעה
            {
                RadioButton r = new RadioButton();
                r.Text = item.ToString();
                r.AutoPostBack = true;
                r.GroupName = "radioButtonList";
                c.Controls.Add(r);
                c.CssClass = "radioButtonCell";
            }
            else //אם התא הוא רגיל ורק צריך להציג בו מידע
                c.Text = item.ToString();
            tr.Cells.Add(c);
        }
        radioIndex++;
        MeetingsTable.Rows.Add(tr);
    }
}

public string GetRadioValue(ControlCollection controls, string groupName)// return the value of the selected radio button, empty string if nothing is selected.
{
    // using Language Intergrated Query (LINQ) in order to find the radio button that is selected in the groupName.
    var selectedRadioButton = controls.OfType<RadioButton>().FirstOrDefault(rb => rb.GroupName == groupName && rb.Checked);
    return selectedRadioButton == null ? string.Empty : selectedRadioButton.Attributes["Value"]; //trinary operator (shortcut of an if expresison)
}


protected void meetButton_Click(object sender, EventArgs e)
{
    //string radioValue = RadioButtonList1.SelectedValue;
    //string radioValue = GetRadioValue(form1.Controls, "radioButtonList");
    string radioValue = GetRadioValue(form1.Controls, "radioButtonList")
    if (!radioValue.Equals("")) // אם נבחרה שעה
    {
        string hour = radioValue;
        Student student = (Student)Session["Student"];
        string id = student.StudentID;
        if (MeetingHelper.Meet(hour, id))
            promptLabel.Text = "הפגישה נקבעה בהצלחה";
        else
            promptLabel.Text = "השעה שבחרת תפוסה, בחר שעה אחרת";
    }
    else
        promptLabel.Text = "בחר שעה";
}

the page will look like this: screenshot

The problem is when i hit the embed meeting button, it will not find the radio button that is selected, after debugging i have noticed there is a problem with the control collection that i am sending, so I tried sending this.Controls or just using Controls. neither helped.

While i could just use a Radio Button List control, and access the selected value attribute, I couldn't manage to display it the way i wanted to look, each radio button in a separate row with the other columns added to the generated table (or some other trick to make the same result).

I have all the using calls that are needed:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text.RegularExpressions;

I really am frustrated at this, please enlighten me!

The MyAdoHelper class is not really relevant for this problem because it doesn't even get into the if statement in the button click call, so i have excluded it.

  • http://stackoverflow.com/questions/11160594/event-handler-for-groupbox-with-radiobuttons-in-c-sharp – vipersassassin Dec 13 '16 at 19:29
  • @viper yes, I have read that already, but when i try to add the event handler to the radiobuttons as so: r.OnCheckedChanged += ... I get an error that the control is inaccessible due to it's protection level. –  Dec 14 '16 at 07:53
  • Are you adding it in the correct class? It can be added in the `InitializeComponent()` section, otherwise, anywhere in the forms class. – vipersassassin Dec 14 '16 at 18:08
  • @vipersassassin I really am not sure what you are talking about, could you further explain? You can see in my code i am adding the radiobutton in the call of the function 'DataBindMeetingsTable' –  Dec 14 '16 at 23:34
  • It would be added in prior to losing scope, so prior to the end of `if(i == 0){ }` – vipersassassin Dec 15 '16 at 16:48

2 Answers2

1

You can read the selected radio button text in following way:

public string GetRadioValue(ControlCollection controls, string groupName)// return the value of the selected radio button, empty string if nothing is selected.
{
    // using Language Intergrated Query (LINQ) in order to find the radio button that is selected in the groupName.
    var selectedRadioButton = controls.OfType<RadioButton>().FirstOrDefault(rb => rb.GroupName == groupName && rb.Checked);
    return selectedRadioButton == null ? string.Empty : selectedRadioButton.Text; //trinary operator (shortcut of an if expresison)
}

and call the method like

string text = GetRadioValue(form1.Controls, "RadioGroupName"); //where form1 is your container id.

and asp:RadioButton look like

<asp:RadioButton ID="radio1" Text="Text for radio button" runat="server" GroupName="RadioGroupName" />
Raj Baral
  • 661
  • 6
  • 19
  • please look at my code, this is what I have been trying to do, but it is not working for me.. –  Dec 14 '16 at 07:52
  • the GetRadioValue always returns null, that is the problem i am looking to solve –  Dec 14 '16 at 07:55
  • I copied the same code from yours and modified this line (return selectedRadioButton == null ? string.Empty : selectedRadioButton.Text) – Raj Baral Dec 14 '16 at 17:49
  • This method return the text of the selected radio button. Look at the calling of the method, I had the same issue while I use the code like yours but I replace selectedRadioButton.Attributes["Value"] by selectedRadioButton.Text it works as expected. Only small change on your code :) – Raj Baral Dec 14 '16 at 17:55
  • hey raj I have tried it and that is surely not the problem, after debugging once again i realized i have a problem with the control collection that is sent into the GetRadioValue method. –  Dec 14 '16 at 23:37
  • What is the control collection i should send if, they are all in a separate table row? do i have to build a control collection each time, or should i just build a radiobuttonlist each time and avoid the linq. –  Dec 14 '16 at 23:48
  • Your aspx code should be inside the form tag with runnet as server, you can use the Id of the form as your control container.. – Raj Baral Dec 15 '16 at 01:17
  • That is the way it is, my form is in a form tag with runat='server' but, it is not working as i described before –  Dec 15 '16 at 13:53
0

After debugging i came to realization that I do not have a control owner or control container that contains all the radioButton Controls. therefore using LINQ is irrelevant, i have used the following code to get the radioValue of the selected radioButton in the Table control:

public string GetRadioValue()
{
    string radioValue = "";
    foreach (TableRow dr in MeetingsTable.Rows)
    {
        int countControls = dr.Cells[0].Controls.Count;
        if (countControls != 0)
        {
            RadioButton r = dr.Cells[0].Controls[0] as RadioButton;
            if (r.Checked)
                radioValue = r.Text;
        }
    }
    return radioValue;
}