Wednesday, December 1, 2010

Radio button in gridview From Code behind C#

In this article I am showing how to use radio button in Datagrid and how to populate from database also how to get value from code behind.
 
 
 
 
<%@ Page Language="C#" MasterPageFile="~/MasterUser.master" Theme="BasicBluecust" AutoEventWireup="true" CodeFile="userpicks.aspx.cs" Inherits="userpicks" Title="User Picks" %>

<asp:Content ID="Content2" ContentPlaceHolderID="mainContent" Runat="Server">

    <table style="width: 100%; height: 100%">
        <tr>
            <td >
            <div>
        &nbsp;&nbsp;&nbsp; &nbsp; &nbsp;
        <table style="vertical-align: sub; direction: ltr; text-indent: 10px; line-height: normal; letter-spacing: normal;  text-align: left; background-color:White" border="1" cellpadding="0" cellspacing="0" width="80%" id="TABLE1" onclick="return TABLE1_onclick()"  >
            <tr>
                <td>
                </td>
                <td align="center" >
                    <asp:Label ID="Label5" runat="server">  Week:      </asp:Label>
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource3"
            DataTextField="Weeks" DataValueField="Weeks">
        </asp:DropDownList>
                    <asp:Label ID="Label2" runat="server" Width="32px"></asp:Label>
                    <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" Visible="False" /></td>
                <td >
                </td>
            </tr>
            <tr>
                <td >
                </td>
                <td align="center" >
                    &nbsp; &nbsp; &nbsp; &nbsp;<asp:Label ID="Label3" runat="server" Width="87px">Enter Name:</asp:Label>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Required!" ControlToValidate="TextBox2" Width="107px"></asp:RequiredFieldValidator></td>
                <td >
                </td>
            </tr>
            <tr>
                <td >
                </td>
                <td >

           
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource2" Width="70%"  HorizontalAlign="Center">
            <Columns>
                <asp:BoundField DataField="week" HeaderText="week" SortExpression="week"  Visible="false"/>
                <asp:TemplateField HeaderText=" ">                   
                    <ItemTemplate>
                        <asp:RadioButton  ID="MyRadioButton" GroupName="1111" Checked="True" runat="server" value='<%# Eval("FromTeam") %>' />
                    </ItemTemplate>
                    </asp:TemplateField>
                <asp:BoundField DataField="FromTeam" HeaderText="Road" ReadOnly="True" SortExpression="FromTeam" />
                <asp:BoundField DataField="at" HeaderText="at" ReadOnly="True" SortExpression="at" Visible="false" />
               <asp:TemplateField HeaderText=" ">                   
                    <ItemTemplate>
                        <asp:RadioButton  ID="MyRadioButton1" GroupName="1111"  runat="server" value='<%# Eval("toTeam") %>' />
                    </ItemTemplate>
                    </asp:TemplateField>
                    
                <asp:BoundField DataField="Toteam" HeaderText="Home" ReadOnly="True" SortExpression="Toteam" />
                <asp:BoundField DataField="date" HeaderText="Date" SortExpression="date" ItemStyle-BackColor="LightYellow" ItemStyle-Width="20" />
                <asp:BoundField DataField="time" HeaderText="Time(EST)" SortExpression="time" ItemStyle-BackColor="LightYellow" ItemStyle-Width="70" ItemStyle-HorizontalAlign="Left" />
               
            </Columns>
        </asp:GridView>
                </td>
                <td >
                </td>
            </tr>
            <tr>
                <td style="height: 26px" >
                </td>
                <td style="height: 26px" align="center" >
                    <asp:Label ID="Label4" runat="server" Width="150px">Last Game's Points:</asp:Label>
        <asp:TextBox ID="TextBox1" runat="server" Width="136px" ></asp:TextBox>&nbsp;
          <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Required!" ControlToValidate="TextBox1"></asp:RequiredFieldValidator></td>
                <td style="height: 26px" >
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td align="center">
                    &nbsp;<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Value must be between 1 and 300" ControlToValidate="TextBox1"
        Type="Integer" MinimumValue="1" MaximumValue="300" ></asp:RangeValidator>
        <asp:Label ID="Label1" runat="server" Width="277px"></asp:Label></td>
                <td>
                </td>
            </tr>
            <tr>
                <td >
                </td>
                <td align="center" >
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
        </td>
                <td >
                </td>
            </tr>
        </table>
        &nbsp; &nbsp;
       

        <br />
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:NFLDBConnectionString %>"
            SelectCommand="SELECT * FROM [vnflsch] WHERE ([week] = @week)">
            <SelectParameters>
                <asp:ControlParameter ControlID="DropDownList1" DefaultValue="week 1" Name="week"
                    PropertyName="SelectedValue" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT DISTINCT [Weeks] FROM [wksaccs] WHERE ([prmsn] = @prmsn)">
            <SelectParameters>
                <asp:Parameter DefaultValue="Y" Name="prmsn" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NFLDBConnectionString %>"
            SelectCommand="SELECT Week FROM [vnflweeks] order by cast(substring(Week,5,3) as int)"></asp:SqlDataSource>
        &nbsp; &nbsp;
                &nbsp;
        &nbsp;&nbsp;
    </div>
            </td>
        </tr>
    </table>
</asp:Content>

 


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;


public partial class userpicks : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

     
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        StringBuilder str = new StringBuilder();
        StringBuilder str1 = new StringBuilder();
        // Select the checkboxes from the GridView control
        str1.Append("insert into uNflsel (uWeek,nicknm,Points,loginm,");
        str.Append("'" + DropDownList1.SelectedItem.Text + "',");
        str.Append("'" + TextBox2.Text + "',");
        str.Append("'" + TextBox1.Text + "',");
        str.Append("'" + Session["loginm"] + "',");
        str.Append("'");


        for (int i = 0; i < GridView1.Rows.Count; i++)
        {

            GridViewRow row = GridView1.Rows[i];
            bool isChecked = ((RadioButton)row.FindControl("MyRadioButton")).Checked;
            bool isChecked1 = ((RadioButton)row.FindControl("MyRadioButton1")).Checked;


            if (isChecked)
            {

                if (GridView1.Rows.Count - 1 != GridView1.Rows[i].RowIndex)
                {
                    str.Append(GridView1.Rows[i].Cells[2].Text);
                    str.Append("','");

                    str1.Append("G" + GridView1.Rows[i].RowIndex);
                    str1.Append(",");

                }
                else
                {
                    str.Append(GridView1.Rows[i].Cells[2].Text);
                    str.Append("')");
                    str1.Append("G" + GridView1.Rows[i].RowIndex);
                    str1.Append(") values (");
                }

            }
            else
                if (GridView1.Rows.Count - 1 != GridView1.Rows[i].RowIndex)
                {
                    str.Append(GridView1.Rows[i].Cells[5].Text);
                    str.Append("','");
                    str1.Append("G" + GridView1.Rows[i].RowIndex);
                    str1.Append(",");
                }
                else
                {
                    str.Append(GridView1.Rows[i].Cells[5].Text);
                    str.Append("')");

                    str1.Append("G" + GridView1.Rows[i].RowIndex);
                    str1.Append(") values (");
                }

        }

        string strSQLSB = str1.ToString() + str.ToString();
        //   Response.Write(strSQLSB);
        //   Response.End();
        SqlDataAdapter myDataAdapter;
        SqlConnection myConnection1 = new SqlConnection(ConnectionString);

        string strSQL = "SELECT * FROM uNflsel where uweek='" + DropDownList1.SelectedItem.Text + "' and nicknm= '" + TextBox2.Text + "' ";

        myDataAdapter = new SqlDataAdapter(strSQL, myConnection1);
        DataSet myDataSet = new DataSet();
        myDataAdapter.Fill(myDataSet, "uNflsel");

        //      Label1.Text = Convert.ToString(myDataSet.Tables["uNflsel"].Rows.Count);


        if ((myDataSet.Tables["uNflsel"].Rows.Count) != 0)
        {
            Label1.Text = "!!! You already did your picks !!!";

        }
        else
        {
            Label1.Text = "!!! Thanks You !!!";
            //insert selection to table
            SqlConnection myConnection = new SqlConnection(ConnectionString);
            SqlCommand myCommand = new SqlCommand(strSQLSB, myConnection);
            myCommand.Connection.Open();
            myCommand.ExecuteNonQuery();
            myCommand.Connection.Close();
        }

 


    }

    private string ConnectionString
    {
        get
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            return connectionString;
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {


        string style = @"<style> .text { mso-number-format:\@;border:.5pt solid black; } </style> ";

        string attachment = "attachment; filename=Report.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        GridView1.RenderControl(htw);
        Response.Write(style);
        Response.Write(sw.ToString());
        Response.End();
    }

 

}

1 comment:

srikanth said...

Thanks a lot:) This is very useful fo me..