Home > Software design >  how to work with the radiobutton in gridview
how to work with the radiobutton in gridview

Time:04-14

i have a gridview which contains the radiobutton in one column and submit button in another column..so if i select one of the radiobutton and click submit it has to pass message to another page..

my gridview code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="stafflogin.aspx.cs" Inherits="gatepass.stafflogin" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
          <div >
             
            
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" BackColor="LightGoldenrodYellow" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
            <Columns>
                 <asp:BoundField DataField="regno" HeaderText="RegNo" SortExpression="regno" />
                 <asp:BoundField DataField="reason" HeaderText="Reason" SortExpression="reason" />
                 <asp:BoundField DataField="type" HeaderText="Type" SortExpression="type" />
                 <asp:BoundField DataField="dol" HeaderText="Date Of Leaving" SortExpression="dol" />
                 <asp:BoundField DataField="tol" HeaderText="Time Of Leaving" SortExpression="tol" />
                 <asp:BoundField DataField="dor" HeaderText="Date Of Reaturn" SortExpression="dor" />
                 <asp:BoundField DataField="tor" HeaderText="Time Of Return" SortExpression="name" />
                <asp:TemplateField HeaderText="Permission">
            <ItemTemplate>  
                                        

<asp:RadioButtonList ID="RadioButtonList1" runat="server">  
    <asp:ListItem  Text="Approved" Value="1"></asp:ListItem>  
      <asp:ListItem  Text="Not Approved" Value="2"></asp:ListItem>  
                                        </asp:RadioButtonList>  
                                    </ItemTemplate>  
        </asp:TemplateField>
                <asp:TemplateField HeaderText="Submit">
            <ItemTemplate>
          <asp:Button Text="Submit" runat="server" CommandName="Submit" OnClick="Submit_click" />
            </ItemTemplate>
        </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>`` 
</body>
</html>

CodePudding user response:

Ok, perhaps one of the MOST common operations we can do with a GridView. A button on a a row, and we click on that button, get the data from that row, and then as you asked, jump to another page and pass that information. Or BETTER is to get the database row PK id.

In fact, in this example? Why not hide the GV, and then say display a div with say more details.

A few things:

Little need to use the command name. Just use the pane jane button click event, and I show how you can get the row information you need.

Next up:

Try to always use the datakeys feature of the gridView. Datakeys is really nice, since it allows you to get the row PK database ID, but NEVER have to expose or display, or EVEN have the database row PK exposed in the data or markup. This is a big deal for reasons of security. (data keys is 100% server side managed for you - and thus rather secure. (users can't change the markup "ID" and thus get or see any database row they want).

Even MORE important the datakeys feature not only gives you free use of the database row PK id, but NOT expose such database PK id's to the client side browser. This also reduces messey parmaters, and even hiddenfields to get use of the row PK id.

Next up:

You really don't need to use the selected index event(s) of the GV. I suppose you can for other purposes, but WE ONLY need a simple button, and then we write up the simple standard plane jane button click event.

So, lets take a simple list of hotels. And we drop in a radio button list (say a hotel rating - good, bad etc.).

And when we click on the button, lets get the row information (in this example the radio button list, and the database row PK id).

so, a simple grid view (note how we don't need the OnSelectedIndexChanged event).

And in fact, note how we did not bother with using CommandName. We really in most cases don't care, nor need, nor even have to bother with all those GridView events.

In most cases the events cause more pain and efforts on your part.

Ok, so, our simple GridView - DO NOTE the Datakeys setting Ok, this:

    <div id="mygrid" runat="server" style="width:60%">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="ID" 
            CssClass="table" OnRowDataBound="GridView1_RowDataBound" >
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName"  />
                <asp:BoundField DataField="LastName" HeaderText="LastName"    />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName"  />
                <asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="270" />

                <asp:TemplateField HeaderText="Rating">
                    <ItemTemplate>
                        <asp:RadioButtonList ID="rbRating" runat="server" RepeatDirection="Horizontal" 
                            CssClass="rBut"
                            SelectedValue='<%# Eval("Rating") %>'>
                            <asp:ListItem Value="0">No Rating</asp:ListItem>
                            <asp:ListItem Value="1">Poor</asp:ListItem>
                            <asp:ListItem Value="2">Fair</asp:ListItem>
                            <asp:ListItem Value="3">Good</asp:ListItem>
                            <asp:ListItem Value="4">Excellent</asp:ListItem>
                            <asp:ListItem Value="5">5 Stars</asp:ListItem>
                        </asp:RadioButtonList>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="View">
                    <ItemTemplate>
                        <asp:Button ID="cmdView" runat="server" Text="View" CssClass="btn"
                            OnClick="cmdView_Click"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

    </div>

And our code to load:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {
        GridView1.DataSource = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName");
        GridView1.DataBind();
    }

    public DataTable MyRst(string strSQL)
    {
        DataTable rstData = new DataTable();
        using (SqlCommand cmdSQL = new SqlCommand(strSQL,
            new SqlConnection(Properties.Settings.Default.TEST4)))
        {
            cmdSQL.Connection.Open();
            rstData.Load(cmdSQL.ExecuteReader());
            cmdSQL.Connection.Dispose();
        }
        return rstData;
    }

and now we have this:

enter image description here

Now, our button code.

Note that you can normal just click on a button to create the click event. However, since the button is "in side" of the GV?

Then just use markup to add the click event. In the button, type in OnClick=

WHEN you hit the "=", then note VERY close inteli-sense pops a choice to create a new event. Select create new event - don't seem like anything occurs, but if you flip to code behind, you see the new button click event.

So, you do this:

enter image description here

So, selecting create new event, and we now see this:

<asp:TemplateField HeaderText="View">
    <ItemTemplate>
        <asp:Button ID="cmdView" runat="server" Text="View" CssClass="btn"
            OnClick="cmdView_Click"/>
    </ItemTemplate>
</asp:TemplateField>

So, now back to code behind, and our button code can do this:

protected void cmdView_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    GridViewRow gRow = btn.NamingContainer as GridViewRow;

    // get database PK id
    int? PKID = GridView1.DataKeys[gRow.RowIndex]["ID"] as int?;
    Debug.Print("Row index click = "   gRow.RowIndex);
    Debug.Print("database PK row ID = = "   PKID);
    Debug.Print("Hotel name = "   gRow.Cells[2].Text);

    RadioButtonList rbList = gRow.FindControl("rbRating") as RadioButtonList;

    Debug.Print("Rating selected value = "   rbList.SelectedItem.Value);
    Debug.Print("Rating selected Text = "   rbList.SelectedItem.Text);

OutPut:

Row index click = 3
database PK row ID = = 2
Hotel name = Ramada Lodge
Rating selected value = 2
Rating selected Text = Fair

So, at this point, we can set PK to session() or whatever, and jump to another page.

Or, we could place a "div" around the GV, and then drop in say a repeater, and put in details of the row.

Say, like this:

    <div id="mydetails" runat="server" style="display:none">
        <asp:Repeater ID="repDetails" runat="server">
        <ItemTemplate>
       <div style="border-style:solid;color:black;width:45%;float:left;padding:10px">
            <div style="padding:5px;text-align:right;float:left">
                <p>Hotel Name: <asp:TextBox ID="HotelName" runat="server" Text ='<%# Eval("HotelName") %>' /></p>
                <p>First Name: <asp:TextBox ID="FirstName" runat="server" Text ='<%# Eval("FirstName") %>' /></p>
                <p>Last Name: <asp:TextBox ID="LastName" runat="server" Text ='<%# Eval("LastName") %>'    /></p>
                <p>City: <asp:TextBox ID="City" runat="server" Text ='<%# Eval("City") %>'  /></p>
                <p>Province: <asp:TextBox ID="Province" runat="server" Text ='<%# Eval("Province") %>'  /></p>
                Active: <asp:CheckBox ID="Active" runat="server" Checked = '<%# Eval("Active") %>'/>
            </div>

            <div style="float:left;margin-left:15px">

                <div style="float:left">
                Hotel Name: <asp:TextBox ID="txtDescription" runat="server" 
                    Text ='<%# Eval("Description") %>' TextMode="MultiLine" Rows="6" Columns="40"  />
                </div>
                <div style="float:left;margin-left:28px">
                    <asp:RadioButtonList ID="rbRating" runat="server"  
                            CssClass="rBut"
                            SelectedValue='<%# Eval("Rating") %>'>
                            <asp:ListItem Value="0">No Rating</asp:ListItem>
                            <asp:ListItem Value="1">Poor</asp:ListItem>
                            <asp:ListItem Value="2">Fair</asp:ListItem>
                            <asp:ListItem Value="3">Good</asp:ListItem>
                            <asp:ListItem Value="4">Excellent</asp:ListItem>
                            <asp:ListItem Value="5">5 Stars</asp:ListItem>
                        </asp:RadioButtonList>
                </div>
            </div>
        </div>
        </ItemTemplate>
        </asp:Repeater>
        <div style="clear:both"></div>
        <br />
        <asp:Button ID="cmdBack" runat="server" Text="Back" CssClass="btn" OnClick="cmdBack_Click" />
     </div>

So, now our button click code becomes this:

        // jump to another page, or say on this page display details
        mygrid.Style.Add("display", "none");
        mydetails.Style.Add("display", "normal");
        repDetails.DataSource = MyRst("SELECT * from tblHotelsA where ID = "   PKID);
        repDetails.DataBind();

Now, when we click on a row, we get this:

enter image description here

However, really at the end of the day?

All you care about is to drop in a plane jane button.

Add a button event. and then in code get the information we need about the row click, and that code was this:

protected void cmdView_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    GridViewRow gRow = btn.NamingContainer as GridViewRow;

    // get database PK id
    int? PKID = GridView1.DataKeys[gRow.RowIndex]["ID"] as int?;
    Debug.Print("Row index click = "   gRow.RowIndex);
    Debug.Print("database PK row ID = = "   PKID);
    Debug.Print("Hotel name = "   gRow.Cells[2].Text);

    RadioButtonList rbList = gRow.FindControl("rbRating") as RadioButtonList;

    Debug.Print("Rating selected value = "   rbList.SelectedItem.Value);
    Debug.Print("Rating selected Text = "   rbList.SelectedItem.Text);

Note how we get "sender" (the button click).

Then we get the Grid View row (this is always namingContainer. This trick works for GridView, ListView - most controls.

And now that we have the Grid view row?

We can get the row index, the pk database id, or pluck out using find control to get the RadioButtonList control.

And in the 2nd div I dropped into the page to show details?

Well, it has a back button - goes back to the GV. But, all we do is hide our "details div", and show the GV div. That back button is thus this:

protected void cmdBack_Click(object sender, EventArgs e)
{
    mygrid.Style.Add("display", "normal");
    mydetails.Style.Add("display", "none");
}
  • Related