Thursday, December 30, 2010

Google Maps Control C# pin

http://www.c-sharpcorner.com/uploadfile/shabdarghata/google-maps-user-control-for-asp-net-part103232008234414pm/google-maps-user-control-for-asp-net-part1.aspx?login=true

Wednesday, December 29, 2010

Update,Delete in a table - SQL injection free C# .net

Update,Delete in a table - SQL injection free C# .net

  void updateADJ()
    {
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        string strSQL;
        strSQL = "update BOINVADJ set IAMEDQTY1=@IAMEDQTY1,IAMEDQTY2=@IAMEDQTY2,"
        + " IABOXQTY=@IABOXQTY,IAGELQTY=@IAGELQTY,IACRYQTY=@IACRYQTY "
        + " WHERE IAID =" + Request["ID"];
        SqlCommand cmd = new SqlCommand(strSQL, myConnection);
        cmd.Parameters.AddWithValue("@IAMEDQTY1",TextBox2.Text  );
        cmd.Parameters.AddWithValue("@IAMEDQTY2", TextBox3.Text);
        cmd.Parameters.AddWithValue("@IABOXQTY", TextBox4.Text);
        cmd.Parameters.AddWithValue("@IAGELQTY", TextBox5.Text);
        cmd.Parameters.AddWithValue("@IACRYQTY", TextBox6.Text);

        myConnection.Open();
        cmd.ExecuteNonQuery();
        myConnection.Close();
    }
    void Deletedata()
    {
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        string strSQL;
        strSQL = "delete from BOINVADJ WHERE IAID=" + Request["ID"];
        SqlCommand cmd = new SqlCommand(strSQL, myConnection);
        cmd.CommandType = CommandType.Text;
        myConnection.Open();
        cmd.ExecuteNonQuery();
        myConnection.Close();
        Response.Redirect("invadj.aspx");
    }

Monday, December 27, 2010

Change Row color in gridview C#

change Row color in gridview C#

public void gridViewMaster_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
    

    if (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Type")).ToString().Trim() == "Media3")
            {
                e.Row.BackColor = Color.Yellow;
            }
    }

Sunday, December 26, 2010

AJAX Extender Control with Pop-up Window

Microsoft AJAX extender controls enhance the client capabilities of standard ASP.NET Web server controls. This example presents AJAX extender control "tbox" that interacts with the HTML DOM elements in a pop-up window. Extender control was developed in Visual Studio 2005.


http://www.codeproject.com/KB/webforms/AJAX-Extender-Control.aspx

Prepare web.config for HTML5 and CSS3

HTML5 and CSS3 introduces some new file types that enables us to create even better websites. We are now able to embed video, audio and custom fonts natively to any web page. Some of these file types are relatively new and not supported by the IIS web server by default. It’s file types like .m4v, .webm and .woff.

http://madskristensen.net/post/Prepare-webconfig-for-HTML5-and-CSS3.aspx


Monday, December 20, 2010

WCF Business Domain - Parent & Child Relationships

WCF by example is a series of articles that describe how to design and develop a WPF client using WCF for communication and NHibernate for persistence purposes. The series introduction describes the scope of the articles and discusses the architect solution at a high level. The source code for the series is found at CodePlex.

WCF by Example - Chapter XIII - Business Domain - Parent & Child Relationships - CodeProject
 
http://www.codeproject.com/KB/architecture/wcfbyexample_chapter13.aspx

Saturday, December 18, 2010

Creating a HTML5 video player control ,asp.net c#

This tutorial will introduce you to the process of ASP.NET server control development. You’ll also see how creating your own controls can simultaneously improve the quality of your Web applications, make you more productive and improve your user interfaces.

ASP.NET custom controls are more flexible than user controls. We can create a custom control that inherits from another server-side control and then extend that control. We can also share a custom control among projects. Typically, we will create our custom control in a web custom control library that is compiled separately from our web application. As a result, we can add that library to any project in order to use our custom control in that project.

ASP.NET 4.0 using Visual Studio 2010 deployment Package/Publish Web tool

There's many ASP.NET developers using Visual Studio who need flexible options and would like a UI to manage deployment tasks. These developers tend to deploy web applications themselves and a few deployment scenarios that exist today where you'll see those developers deploying applications themselves:

  • Small to mid-sized companies where the developer sees the application end to end, often a solo developer, however s/he might be on a small team.
  • Individual consultants or small consultancies that need to deploy remotely, often using FTP or FTPS (secure FTP).
  • Small to mid-sized teams that don't have automated deployment or CI in place and are in charge of their own application deployments.

The central theme is that all three types of teams are all responsible for their own application deployments. If you work in a dev shop similar to one of these, you'll find Visual Studio 2010's Web Deploy feature is quite handy and should meet most of your deployment needs out of the box. But it's also easily extensible to get those few unique deployment tasks you may have configured and ready to go.

http://rachelappel.com/deployment/making-asp-net-deployment-easy-with-the-package-publish-web-tool/

Thursday, December 16, 2010

Send Email GridView as an Excel attachment C#, asp.net

Following is the complete code for Send Email  GridView data  as an Excel attachment, any question please post comment.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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"
            DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="AccessNo" HeaderText="AccessNo"
                    SortExpression="AccessNo" />
                <asp:BoundField DataField="SerialNo" HeaderText="SerialNo"
                    SortExpression="SerialNo" />
                <asp:BoundField DataField="ActivationDate" HeaderText="ActivationDate"
                    SortExpression="ActivationDate" />
                <asp:BoundField DataField="Status" HeaderText="Status"
                    SortExpression="Status" />
                <asp:BoundField DataField="StatusDate" HeaderText="StatusDate"
                    SortExpression="StatusDate" />
                <asp:BoundField DataField="OrderType" HeaderText="OrderType"
                    SortExpression="OrderType" />
                <asp:BoundField DataField="OrderNo" HeaderText="OrderNo"
                    SortExpression="OrderNo" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:JDE_RKConnectionString %>"
            SelectCommand="SELECT top 10 [AccessNo], [SerialNo], [ActivationDate], [Status], [StatusDate], [OrderType], [OrderNo] FROM jde_rk.dbo.a276185">
        </asp:SqlDataSource>
   
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
   
    </div>
    </form>
</body>
</html>

 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;

using System.Net.Mail;

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

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


    void sndmailattch()
    {
    
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.RenderControl(htw);
        MailMessage mail = new MailMessage();
        mail.IsBodyHtml = true;
        mail.To.Add(new MailAddress("rajeevk@visli.net"));
        mail.Subject = "Inventory Report";

        System.Text.Encoding enc = System.Text.Encoding.ASCII;
        byte[] myByteArray = enc.GetBytes(sw.ToString());
        System.IO.MemoryStream memAtt = new System.IO.MemoryStream(myByteArray, false);
        mail.Attachments.Add(new Attachment(memAtt,"inventory.xls"));
        mail.Body = "Inventory report brother..";

        SmtpClient smtp = new SmtpClient();
        mail.From = new MailAddress("rajeevk@visli.net", "Rajeev Kumar");
        smtp.Host = "mail.visli.net";
       
        //smtp.UseDefaultCredentials = false;
        //smtp.Credentials = new System.Net.NetworkCredential(@"UserName", "Password");
        //smtp.EnableSsl = true;
      
        smtp.Send(mail);

    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }
}

Wednesday, December 15, 2010

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.-solution

Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
solution
      SqlConnection myConnection = new SqlConnection(ConnectionStringrk);
        string strSQL;
        strSQL = "runube_acctbal  'R55570001','IVG0001','" + sbledgr.ToString() + "','" + txtFdate.Text + "','" + txttdate.Text + " '";
    
        SqlCommand cmd = new SqlCommand(strSQL, myConnection);
        cmd.CommandTimeout = 300; //5 min.
        cmd.CommandType = CommandType.Text;
        myConnection.Open();
        cmd.ExecuteNonQuery();
        myConnection.Close();

Monday, December 13, 2010

JD Edwards Fix Half posted IB Error batch (Sales Invoice)

 Today my finance department's beautiful controller told me for a particular company's trial Balance is off by some millions.
   So I started troubleshooting, why we have this problem,  so first I  ran a JD Edwards report Batch and Company within Batch out of Balance Report (R09706).
I found a batch in this report error amount showing approximately same we off for that company. try to post that batch got error in work center  
hundreds of similar error-  The AA ledger type for 8/23/2010 ,document 928136 is out of balance by 29778.26
 
I did following steps in order to fix this problem.

1> Took backup for this batch for F0911 and F03B11.

2> Deleted all AE from F0911 for this batch using SQL.

3> Updated F0911 RPpost field with blank.

4> Updated F03B11 RPpost with P.

6> Ran Batch posting program(R09801) from P0011.

6> Batch posted correctly.

7> From F0911 batch Backup took Distinct GLAID and ran Repost program (R099102) to updated account balance.

 

 

 

Note: Use SQL on JD Edwards table with own risk.

 

Sunday, December 12, 2010

Silverlight 4 textbox Validation c#

Silverlight 4 has some new ways for validate input values (some new approaches to implement validation in your application). First approach is DataAnnotation. In this case you should describe validation rules with attributes. Two other ways (both of them is came with Silverlight 4) – you should implement one of interfaces for your ViewModel: IDataErrorInfo or INotifyDataErrorInfo. I want to talk about all of these approaches, about pros and cons of using each of them. Goal of this article to get a best way to implement validation of input values in my and your applications.

http://www.codeproject.com/KB/silverlight/Silverlight4_Validation.aspx

Project estimation with Use Case Points using Enterprise Architect (EA)

Project estimation is one of the most challenging duties of project managers. Among various estimation methods, Use Case Points is the most reliable method. If you are not familiar with UCP please read this article.

As you may know, Use Case Points method involves different factors and needs calculation. For most software project managers it seems difficult and time consuming to use it manually.

In this article I will show you how to estimate a software project using Sprax Enterprise Architect (EA) which is a famous CASE tool. (I used EA 7.5 in this article)

Based on Rational Unified Process (RUP), In order to estimate software projects duration, you need to recognize the project features and requirements first. This leads you to Use Cases that are cores of a software project analysis model and you cannot estimate any software project without recognizing its Use Cases. Requirements, Features and Use Cases recognition are usually done in the first phase of RUP, Inception.

http://www.codeproject.com/KB/architecture/UCP_EA.aspx

Friday, December 10, 2010

ASP.NET MVC Diagnostics Using NuGet

Sometimes, despite your best efforts, you encounter a problem with your ASP.NET MVC application that seems impossible to figure out and makes you want to pull out your hair. Or worse, it makes you want to pull out my hair. In some of those situations, it ends up being a PEBKAC issue, but in the interest of avoiding physical harm, I try not to point that out.



Making your own ViewEngine MVC

http://buildstarted.com/2010/11/22/making-your-own-viewengine-with-markdown/

Wednesday, December 8, 2010

JD Edwards - SQL for Finding all the Releases from Blankets (OB and OHs)


JD Edwards - SQL for Finding all the Releases from Blankets (OB and OHs)

select pddoco OH,pddcto,pdoorn OB,pdlitm,pddsc1,pduorg,
DATEADD(dy, cast(pdtrdj as varchar(10)) % 1000, DATEADD(yy, cast(pdtrdj as varchar(10)) / 1000,-1))  pdtrdj
from proddta.f4311
where pdocto='OB' and pdlttr<>980
and pdoorn in
(16332,16334,17897,17924,17925,17699,18146,18155,18156,18164,18494,18218,18492,18527,18528,18531,18162)
order by pddoco

Silverlight dynamic point to point animation with EasingFunction

Silverlight Next: Silverlight dynamic point to point animation with EasingFunction

Silverlight Gird,Canvas ,Controls and Layout

The layout system works in a similar way to the way an aspx page is constructed. Since XAML is a markup language that can be viewed to work in a similar way to aspx, this makes it a little easier to visualise when working with it. Simply put, to get started you would need to choose a layout type to put controls on. From what I have read, there are three types of layouts that can be used: Canvas, Grid, StackPanel.
 
http://www.codeproject.com/Articles/132079/Silverlight-Journey-Controls-and-Layout.aspx

Exploring Reactive Extensions (Rx) through Twitter and Bing Maps Mashups

Whether reacting to user-input or handling responses from web services, Silverlight applications are typically asynchronous in nature. The framework provides UI control that fire events in response to user interactions, there are also classes like the DispatcherTimer and WebControl that perform some background work, firing events which are helpfully marshalled back onto the UI thread. However, Silverlight, and the other .NET UI frameworks, lack a way of orchestrating these asynchronous activities.

In this article I will look at how the Reactive Extensions (Rx) library provides a common interface for asynchronous events and actions giving  a consistent way to composite, orchestrate and marshal events between threads (and also have some fun creating a few cool mashups along the way!)

This article builds a couple of Rx powered Silverlight applications step by step, the final one being a Twitter / Bing Maps mashup that shows the location of snowfall in the UK based on users Tweets to the #uksnow hashtag.
 
 
http://www.codeproject.com/KB/silverlight/ExploringRx.aspx

Tuesday, December 7, 2010

Unhandled Error in Silverlight Application Value does not fall within the expected range. at MS.Internal.XcpImports.CheckHResult(UInt32 hr)

how to fix this?
Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; WOW64; Trident/4.0; GTB6.6; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)
Timestamp: Tue, 7 Dec 2010 22:47:22 UTC


Message: Unhandled Error in Silverlight Application Value does not fall within the expected range.   at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
   at MS.Internal.XcpImports.CaptureGraph_Start(CaptureSource Source)
   at System.Windows.Media.CaptureSource.Start()
   at SilverlightApplication2.MainPage.StartWebCam()
   at SilverlightApplication2.MainPage.button1_Click_1(Object sender, RoutedEventArgs e)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
Line: 1
Char: 1
Code: 0
URI: http://10.1.3.37/slvtest/


Message: Unhandled Error in Silverlight Application Value does not fall within the expected range.   at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
   at MS.Internal.XcpImports.CaptureGraph_Start(CaptureSource Source)
   at System.Windows.Media.CaptureSource.Start()
   at SilverlightApplication2.MainPage.StartWebCam()
   at SilverlightApplication2.MainPage.button1_Click_1(Object sender, RoutedEventArgs e)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
Line: 1
Char: 1
Code: 0
URI: http://10.1.3.37/slvtest/

 

Unrecognized attribute 'targetFramework'.

 

Server Error in '/slvtest' Application.

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Unrecognized attribute 'targetFramework'.

Source Error:

Line 8:  <configuration> Line 9:      <system.web> Line 10:         <compilation debug="true" targetFramework="4.0" /> Line 11:     </system.web> Line 12: 

Source File: C:\SilverlightApplication2\SilverlightApplication2.Web\web.config    Line: 10


Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573
 
 
solution rename your web.config to web111.config, if you dont need web.config file
 
if you need then change version to 4.0.21006.1 

Error: Assembly System.Windows.Controls.DomainServices was not found. Siliverlight C#

use this :   xmlns:riaControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices"

http://msdn.microsoft.com/en-us/library/ee707363(VS.91).aspx

Thursday, December 2, 2010

Silverlight Working with Animations Programmatically

There are times when you may want to change the properties of an animation dynamically (on the fly). For example, you might want to adjust the behavior of an animation that is applied to an object, depending on the object's current location in the layout, what kind of content the object contains, and so on. You can manipulate animations dynamically by using procedural code (for example, C# or Visual Basic).
 
http://msdn.microsoft.com/en-us/library/cc189069$v=VS.95$.aspx




Silverlight Animation Overview

In Silverlight, animation can enhance your graphical creation by adding movement and interactivity. By animating a background color or applying an animated Transform, you can create dramatic screen transitions or provide helpful visual cues.

http://msdn.microsoft.com/en-us/library/cc189019$VS.95$.aspx#introducing_animations



 


Error in Silverlight Application Code: 2104 Category: InitializeError Message: Could not download the Silverlight application. Check web server settings

Error: Unhandled Error in Silverlight Application Code: 2104 Category: InitializeError Message: Could not download the Silverlight application. Check web server settings
just started silverlight got thsi error.
How to fix this error?

I finally found the solution to this problem.

It seems like the MIME types for .xap and .xaml may need to be added to the individual website, not just the root. When I did this the problem went away.

It still leaves me with a problem on my hosted environment -- I guess I will have to get my web host support guys to add the MIME types to my website।

http://forums.silverlight.net/forums/p/111126/309207.aspx

JD Edwards How to fix IB Batch (invoice) error?

When you are getting error and not able to post sales update IB batches, you can do following steps:-
1. Check the peroid for that month is open or not if its not open , open that month and try posting.
2. check the work center for detail error messages if you are getting following error messages , see which particular invoice is giving error, get the
tax rate area for that invoice and type in fast path P4008, and correct the end date for tax rate area and then post the batch.

Subject       : Error: Tax Area Invalid
CAUSE . . . .  The tax area does not exist in the Tax Area Master
               file (F4008).  A tax area having an effective date prior
               to the tax point date (service date) must exist in the
               Tax Area file.
RESOLUTION. .  Change the service date if applicable or change the tax area to
               a valid tax area.
               NOTE:  The service date is not applicable in certain
                      circumstances.  For example; Supplier Master, Customer
                      Master and Business Unit Revisions.


3.if you are getting error particular account not defined in AAI then, type DMAAI in fast path and fix that account or define that account in distribution aai.
4. if you are getting account inactive , then check account master for that particular account and make changes like allow all posting etc and then try to post.

 

Wednesday, December 1, 2010

Twitter New API C# post message from database continuous

In following sample I can post messages on twitter , using Twitter New API , getting messages from database
and post in a defined interval. this is very good tool for advertisement.


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.Data.SqlClient;
using System.Net;
using System.IO;
using oAuthExample;
using System.Threading;


public partial class autoposttest : System.Web.UI.Page
{

    string txtMSGtweet;
    string txttweet = "dut yaar dimag mat kharab kar..  ..";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            MyLabel.Text = System.DateTime.Now.ToString();
        }

        if (Session["Usrid"] == null)
        {
            // Response.Redirect("login.aspx");
        }
        else
        {
            labuser.Text = "Hi " + Session["Usrid"].ToString();
        }
       getmsg();
   
    }

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        Label1.Text = " : " + DateTime.Now.ToLongTimeString();
        getmsg();

    }


   
    public void getmsg()
    {
        string url = "";
        string xml = "";
        oAuthTwitter oAuth = new oAuthTwitter();

        if (Request["oauth_token"] == null)
        {
            oAuth.CallBackUrl = "http://127.0.0.1/twitterpost/autoposttest.aspx";
            Response.Redirect(oAuth.AuthorizationLinkGet());
        }
        else
        {
            oAuth.AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]);
            //Response.Write(oAuth.TokenSecret.ToString());
            //Response.End();
            if (oAuth.TokenSecret.Length > 0)
            {


                SqlConnection myConnection = new SqlConnection(ConnectionString);
                char YNtxt = 'N';
                string strSQL = "select top 5 * from TwitAutoMsg where TwitYN= '" + YNtxt + "'";


                SqlCommand cmd = new SqlCommand(strSQL, myConnection);
                myConnection.Open();
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                while (myReader.Read())
                {

                    txtMSGtweet = myReader["TwitMsg"].ToString();

                    //                    Response.Write(txtMSGtweet + "<br>");

                    string strTwitID = myReader["TwitID"].ToString();

                    updatedata(strTwitID);
                    //SubmitUserMsg();

                    url = "http://twitter.com/statuses/update.xml";
                    xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, url, "status=" + oAuth.UrlEncode(txtMSGtweet.ToString()));
                    apiResponse.InnerHtml = Server.HtmlEncode(xml);
                    Thread.Sleep(12000);
                    Label4.Text = "<br>Last Message Posted - " + txtMSGtweet.ToString();
                }

                myReader.Close();
                myConnection.Close();
            }
        }
    }

    public void updatedata(string strTwitID1)
    {
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        string strSQL;
        int strTwitIDInt = Convert.ToInt32(strTwitID1);
        char YNtxtu = 'Y';
        strSQL = "Update TwitAutoMsg set TwitYN='" + YNtxtu + "' where TwitID=" + strTwitID1;
        SqlCommand cmd = new SqlCommand(strSQL, myConnection);
        cmd.CommandType = CommandType.Text;
        myConnection.Open();
        cmd.ExecuteNonQuery();
        myConnection.Close();
    }

    private string ConnectionString
    {
        get
        {
            string connectionString = ConfigurationManager.ConnectionStrings["VISLI_DVConnectionString"].ConnectionString;
            return connectionString;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        //Response.Write("asas");
        Label1.Text = " : " + DateTime.Now.ToLongTimeString();
        //  getmsg();
    }
}

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();
    }

 

}