Wednesday, October 14, 2009

4

Send Email With Attachment in asp.net

In this example i am going to describe how to send email with attachment in ASP.NET using fileUpload Control.
I am saving the uploaded file into memory stream rather then saving it on server.



And for this example i m using Gmail SMTP server to send mail, this code also works fine with any SMTP Server.

For sending Email in ASP.NET , first of all we need to add Syatem.Net.Mail namespace in code behind of aspx page. 

In my previous article i describe how to send mail using gmail in asp.net 





Create the page as shown in the image above, put textbox for message and FileUpload Control for adding the file attachment.

Write below mentioned code in click event of Send button in Code behind of page

C# Code Behind
using System;
using System.Data;
using System.Configuration;
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.Net.Mail;

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

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(txtTo.Text);
        //mail.To.Add("amit_jain_online@yahoo.com");
        mail.From = new MailAddress(txtFrom.Text);
        mail.Subject = txtSubject.Text;
        mail.Body = txtMessage.Text;
        mail.IsBodyHtml = true;

        //Attach file using FileUpload Control and put the file in memory stream
        if (FileUpload1.HasFile)
        {
            mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
        }
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
        smtp.Credentials = new System.Net.NetworkCredential
             ("YourGmailID@gmail.com", "YourGmailPassword");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = true;
        smtp.Send(mail);

    }
}


VB.NET Code Behind
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Net.Mail

Public Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        
    End Sub
    Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim mail As New MailMessage()
        mail.[To].Add(txtTo.Text)
        'mail.To.Add("amit_jain_online@yahoo.com");
        mail.From = New MailAddress(txtFrom.Text)
        mail.Subject = txtSubject.Text
        mail.Body = txtMessage.Text
        mail.IsBodyHtml = True
        
        'Attach file using FileUpload Control and put the file in memory stream
        If FileUpload1.HasFile Then
            mail.Attachments.Add(New Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName))
        End If
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        'Or Your SMTP Server Address
        smtp.Credentials = New System.Net.NetworkCredential("YourGmailID@gmail.com", "YourGmailPassword")
        'Or your Smtp Email ID and Password
        smtp.EnableSsl = True
            
        smtp.Send(mail)
    End Sub
End Class
Build and run the application to test the code

Hope this helps

Continue Reading...

Saturday, September 12, 2009

0

Open PopUp Window Update Refresh Parent Values From Child ASP.NET

In this example i am going to describe how to open popup window from aspx page with values from parent page, and update or refresh values in parent window from child or popup window using javascript and ClientScript.RegisterStartupScript method in ASP.NET

I have added to labels in Default.aspx page and one button to open popup window.

I've also added a PopUp.aspx page which is having two textboxes and a button to update lable values of parent page.

The textboxes in popup window are populated with Text values of lables in parent page (Default.aspx), after making changes in textbox values i'm updating values back in parent page.
















HTML source of Default.aspx (parent) page is
<form id="form1" runat="server">
<div>
First Name :
<asp:Label ID="lblFirstName" runat="server" Text="amiT">
</asp:Label><br />
 <br />
Last Name:&nbsp;
<asp:Label ID="lblLastName" runat="server" Text="jaiN">
</asp:Label><br />
<br />
<asp:Button ID="btnPop" runat="server" Text="Click To Edit Values" />
</div>
</form>
Write this Javascript in Head section of Default.aspx page

In this i m getting values of lables and passing them to popuup page as querystrings
write this code Page_Load event of Default.aspx (parent) page
C# code behind
protected void Page_Load(object sender, EventArgs e)
{
 string updateValuesScript = 
@"function updateValues(popupValues)
{
 document.getElementById('lblFirstName').innerHTML=popupValues[0];
 document.getElementById('lblLastName').innerHTML=popupValues[1];
}";
        
this.ClientScript.RegisterStartupScript(Page.GetType(), 
"UpdateValues", updateValuesScript.ToString(), true);
btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')");
}

VB.NET code behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim updateValuesScript As String = "function updateValues(popupValues)" & vbCr & vbLf & "{" & vbCr & vbLf & " document.getElementById('lblFirstName').innerHTML=popupValues[0];" & vbCr & vbLf & " document.getElementById('lblLastName').innerHTML=popupValues[1];" & vbCr & vbLf & "}"
    
    Me.ClientScript.RegisterStartupScript(Page.[GetType](), "UpdateValues", updateValuesScript.ToString(), True)
    btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')")
End Sub

And this is the HTML code for PopUp.aspx(child) page
<form id="form1" runat="server">
<div>
First Name :
<asp:TextBox ID="txtPopFName" runat="server" Width="113px">
</asp:TextBox><br />
<br />
Last Name:<asp:TextBox ID="txtPopLName" runat="server" 
                       Width="109px">
</asp:TextBox><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" 
            Text="Button" /></div>
</form>
Code behind for PopUp.aspx
C# code behind
protected void Page_Load(object sender, EventArgs e)
{
 string updateParentScript = 
 @"function updateParentWindow()
 {                                                                               
   var fName=document.getElementById('txtPopFName').value;     
   var lName=document.getElementById('txtPopLName').value;   
   var arrayValues= new Array(fName,lName);
   window.opener.updateValues(arrayValues);       
   window.close(); 
 }";
 this.ClientScript.RegisterStartupScript(this.GetType(), 
     "UpdateParentWindow", updateParentScript, true);
 if (!IsPostBack)
 {
   txtPopFName.Text = Request["fn"];
   txtPopLName.Text = Request["ln"];
 }
   Button1.Attributes.Add("onclick", "updateParentWindow()");
}
VB.NET code behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim updateParentScript As String = "function updateParentWindow()" & vbCr & vbLf & " {                                                                               " & vbCr & vbLf & "   var fName=document.getElementById('txtPopFName').value;     " & vbCr & vbLf & "   var lName=document.getElementById('txtPopLName').value;   " & vbCr & vbLf & "   var arrayValues= new Array(fName,lName);" & vbCr & vbLf & "   window.opener.updateValues(arrayValues);       " & vbCr & vbLf & "   window.close(); " & vbCr & vbLf & " }"
    Me.ClientScript.RegisterStartupScript(Me.[GetType](), "UpdateParentWindow", updateParentScript, True)
    If Not IsPostBack Then
        txtPopFName.Text = Request("fn")
        txtPopLName.Text = Request("ln")
    End If
    Button1.Attributes.Add("onclick", "updateParentWindow()")
End Sub

Hope this helps

Download sample code attached




Continue Reading...

Tuesday, September 8, 2009

1

AutoCompleteExtender TextBox CompletionList Width Ajax ASP.NET

In this example i am going to describe how to set Width of Completion List in Ajax AutoComplete Extender TextBox.
The default behavior of completion list takes width equal to the width of textbox. we can change this behavior by applying some CSS style to set the width we want. default width is as shown below in the Image.


To read how to implement AutoComplete extender TextBox in GridView , go through link below
Ajax AutoComplete Extender Textbox in Edit mode of GridView

To read how to Add Progress Image in AutoComplete TextBox, go through link mentioned below
Progress Image in Ajax AutoComplete TextBox


As obvious from the image above , width of completion list is equals to the width of textbox, to fix this issue write the CSS script mentioned below in Head section of html source of page
<head runat="server">
    <title>Progress Image in AutoComplete TextBox</title>
<style>
        .AutoExtender
        {
            font-family: Verdana, Helvetica, sans-serif;
            font-size: .8em;
            font-weight: normal;
            border: solid 1px #006699;
            line-height: 20px;
            padding: 10px;
            background-color: White;
            margin-left:10px;
        }
        .AutoExtenderList
        {
            border-bottom: dotted 1px #006699;
            cursor: pointer;
            color: Maroon;
        }
        .AutoExtenderHighlight
        {
            color: White;
            background-color: #006699;
            cursor: pointer;
        }
        #divwidth
        {
          width: 150px !important;    
        }
        #divwidth div
       {
        width: 150px !important;   
       }
 </style>
</head>
The code in bold is setting the width of completion list, you can change the dimensions according to your needs.

Now Put a div with id "divwidth" above the html source of autocomplete extender
<div ID="divwidth"></div>

and add this line in autocomplete extender HTML source

CompletionListElementID="divwidth"

The complete html source of AutoComplete Extender will look like
<asp:TextBox ID="txtAutoComplete" runat="server" Width="252px">
</asp:TextBox>   
<div ID="divwidth"></div>
<ajaxToolkit:AutoCompleteExtender runat="server" 
             ID="AutoComplete1"
             BehaviorID="autoComplete"
             TargetControlID="txtAutoComplete"
             ServicePath="AutoComplete.asmx" 
             ServiceMethod="GetCompletionList"
             MinimumPrefixLength="1" 
             CompletionInterval="10"
             EnableCaching="true"
             CompletionSetCount="12"
             CompletionListCssClass="AutoExtender"
             CompletionListItemCssClass="AutoExtenderList"
             CompletionListHighlightedItemCssClass
             ="AutoExtenderHighlight"
             CompletionListElementID="divwidth">
<ajaxToolkit:AutoCompleteExtender>

And this is how the AutoComplete TextBox will look like


Hope this helps


Continue Reading...

Monday, September 7, 2009

8

Detect Page Refresh In ASP.NET

If you have created a aspx page using C# and ASP.NET and have put a button on it. And in the Click event of this button if you are inserting some data in database , after click if user refresh the page than click event gets fired again resulting data insertion to database again, to stop events on the page getting fired on browser refresh we need to write bit of code to avoid it

In this example i've put a Label and a Button on the page, on click the label Text becomes Hello and when i refresh the page label's text again becomes Hello

<%@ 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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label><br />
<br />
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click"
Text="Button" /></div>
</form>
</body>
</html>


Now in the Page_Load event i m creating a Session Variable and assigning System date and time to it , and in Page_Prerender event i am creating a Viewstate variable and assigning Session variable's value to it
Than in button's click event i am checking the values of Session variable and Viewstate variable if they both are equal than page is not refreshed otherwise it has been refreshed
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}

}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() ==
ViewState["CheckRefresh"].ToString())
{
Label1.Text = "Hello";
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}
else
{
Label1.Text = "Page Refreshed";
}
}

protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
}


Download the Sample Code



Continue Reading...

Tuesday, September 1, 2009

2

Pass Send GridView Row Value/Data Using Hyperlink in ASP.NET

In this example i am going to describe how to pass transfer or send GridView data or values from GridView row to Other asp.net page using hyperlink in GridView.

I've put a hyperlink column in gridview to pass values through querystring, and using request.querystring on the second page to retrieve values.

You would also like to read
LinkButton in GridView and QueryString in ASP.NET to pass data










We need to set DataNavigateUrlFields and DataNavigateUrlFormatString properties of hyperlink in gridview to pass the row data 

HTML markup of the page look like
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="ID,Name,Location" 
DataNavigateUrlFormatString=
"Default2.aspx?id={0}&name={1}&loc={2}" 
Text="Transfer values to other page" />
<asp:BoundField DataField="ID" HeaderText="ID" 
                SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" 
                SortExpression="Name" />
<asp:BoundField DataField="Location" HeaderText="Location" 
                SortExpression="Location" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]">
</asp:SqlDataSource>

Now write code mentioned below to retrieve values on Default2.aspx page
C# code behind
protected void Page_Load(object sender, EventArgs e)
    {
        string strID = Request.QueryString["id"];
        string strName = Request.QueryString["name"];
        string strLocation = Request.QueryString["loc"];
        lblID.Text = strID;
        lblName.Text = strName;
        lblLocation.Text = strLocation;
    }
VB.NET code behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim strID As String = Request.QueryString("id")
    Dim strName As String = Request.QueryString("name")
    Dim strLocation As String = Request.QueryString("loc")
    lblID.Text = strID
    lblName.Text = strName
    lblLocation.Text = strLocation
End Sub

Hope this helps



Continue Reading...

Saturday, August 29, 2009

1

NULL In GridView EVAL Calling Serverside Method In ItemTemplate

In this example i am going to describe how to handle NULL values from DataBase in Eval method of GridView ItemTemplate or How to call Server side method written in code behind in ItemTemplate of GridView.


My Table in database look like as shown in image below, some columns contains NULL values and i'll be showing "No Records Found" instead of NULL values in GridView.

To achieve this i've written a Method in code behind and will be calling this method in ItemTemplate of GridView.




Html source of GridView
<asp:GridView ID="GridView1" runat="server" 
              DataSourceID="SqlDataSource1" 
              AutoGenerateColumns="false">
<Columns>
<asp:BoundField ShowHeader="true" DataField="ID" 
                              HeaderText="ID" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" 
           Text='<%# CheckNull(Eval("Name")) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" 
           Text='<%# CheckNull(Eval("Location")) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT ID, Name, Location FROM Details">
</asp:SqlDataSource>

In above code i am calling server side method CheckNull written in code behind from ItemTemplate of GridView which check the NULL values and change it as we want.
C# code for the CheckNull method
protected string CheckNull(object objGrid)
    {
        if (object.ReferenceEquals(objGrid, DBNull.Value))
        {
            return "No Record Found";
        }
        else
        {
            return objGrid.ToString();
        }
     }
VB.NET code behind
Protected Function CheckNull(ByVal objGrid As Object) As String
    If Object.ReferenceEquals(objGrid, DBNull.Value) Then
        Return "No Record Found"
    Else
        Return objGrid.ToString()
    End If
End Function


And this is how gridview will render


Hope this helps


Continue Reading...

Thursday, August 27, 2009

17

Send Email Using Gmail in ASP.NET

If you want to send email using your Gmail account or using Gmail's smtp server in ASP.NET application or if you don't have a working smtp server to send mails using your ASP.NET application or aspx page than sending e-mail using Gmail is best option.

you need to write code like this

First of all add below mentioned namespace in code behind of aspx page from which you want to send the mail.

using System.Net.Mail;

Now write this code in click event of button

C# code

protected void Button1_Click(object sender, EventArgs e)
{
  MailMessage mail = new MailMessage();
  mail.To.Add("jainamit.agra@gmail.com");
  mail.To.Add("amit_jain_online@yahoo.com");
  mail.From = new MailAddress("jainamit.agra@gmail.com");
  mail.Subject = "Email using Gmail";

  string Body = "Hi, this mail is to test sending mail"+ 
                "using Gmail in ASP.NET";
  mail.Body = Body;

  mail.IsBodyHtml = true;
  SmtpClient smtp = new SmtpClient();
  smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
  smtp.Credentials = new System.Net.NetworkCredential
       ("YourUserName@gmail.com","YourGmailPassword");
//Or your Smtp Email ID and Password
  smtp.EnableSsl = true;
  smtp.Send(mail);
}

VB.NET code

Imports System.Net.Mail
 
Protected  Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
  Dim mail As MailMessage =  New MailMessage() 
  mail.To.Add("jainamit.agra@gmail.com")
  mail.To.Add("amit_jain_online@yahoo.com")
  mail.From = New MailAddress("jainamit.agra@gmail.com")
  mail.Subject = "Email using Gmail"
 
  String Body = "Hi, this mail is to test sending mail"+ 
                "using Gmail in ASP.NET"
  mail.Body = Body
 
  mail.IsBodyHtml = True
  Dim smtp As SmtpClient =  New SmtpClient() 
  smtp.Host = "smtp.gmail.com" //Or Your SMTP Server Address
  smtp.Credentials = New System.Net.NetworkCredential
       ("YourUserName@gmail.com","YourGmailPassword")
  smtp.EnableSsl = True
  smtp.Send(mail)
End Sub


You also need to enable POP by going to settings > Forwarding and POP in your gmail account

Change YourUserName@gmail.com to your gmail ID and YourGmailPassword to Your password for Gmail account and test the code.

If your are getting error mentioned below
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

than you need to check your Gmail username and password.

If you are behind proxy Server then you need to write below mentioned code in your web.config file
<system.net>
<defaultProxy>
<proxy proxyaddress="YourProxyIpAddress"/>
</defaultProxy>
</system.net>

If you are still having problems them try changing port number to 587
smtp.Host = "smtp.gmail.com,587";

If you still having problems then try changing code as mentioned below
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = False;
smtp.Credentials = new System.Net.NetworkCredential
("YourUserName@gmail.com","YourGmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);

Hope this helps



Continue Reading...

Wednesday, August 26, 2009

7

RadioButtonList DropDownList In GridView Edit Mode In ASP.NET

In this example i am going to describe how to implement RadioButtonList and DropDOwnList in Edit mode of GridVIew using EditItemTemaplate in ASP.NET C# and VB.NET.

RadioButton and DropDOwnList are selected in edit mode based on value saved in DataBase



HTML markup of aspx page is mentioned below
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1" 
              OnRowDataBound="GridView1_RowDataBound" 
              OnRowUpdated="GridView1_RowUpdated" 
              OnRowUpdating="GridView1_RowUpdating" 
              OnRowEditing="GridView1_RowEditing">
 <Columns>
 <asp:TemplateField HeaderText="ID">
 <ItemTemplate>
 <asp:Label ID="lblID" runat="server" Text='<%#Eval("ID") %>'>
 </asp:Label>
 </ItemTemplate>
 </asp:TemplateField>
 
 <asp:BoundField DataField="Name" HeaderText="Name" 
                 SortExpression="Name" />
 <asp:TemplateField HeaderText="Gender">
 <ItemTemplate>
 <asp:Label ID="lblGender" runat="server" 
            Text='<%#Eval("Sex") %>'>
 </asp:Label>
 </ItemTemplate>
 <EditItemTemplate>
 <asp:RadioButtonList ID="rbGenderEdit" runat="server">
 <asp:ListItem>Male</asp:ListItem>
 <asp:ListItem>Female</asp:ListItem>
 </asp:RadioButtonList>
 </EditItemTemplate>
 </asp:TemplateField>
 
 <asp:TemplateField HeaderText="Marital Status">
 <ItemTemplate>
 <asp:Label ID="lblStatus" runat="server" 
            Text='<%#Eval("MaritalStatus") %>'>
 </asp:Label>
 </ItemTemplate>
 <EditItemTemplate>
 <asp:DropDownList ID="ddlStatusEdit" runat="server">
 <asp:ListItem>Single</asp:ListItem>
 <asp:ListItem>Married</asp:ListItem>
 </asp:DropDownList>
 </EditItemTemplate>
 </asp:TemplateField>
 <asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Sex], [MaritalStatus] 
               FROM [Details]" 
UpdateCommand="Update Details Set [Name]=@Name, [Sex]=@Sex, 
              [MaritalStatus]=@MaritalStauts Where [ID]=@ID">
   <UpdateParameters>
       <asp:Parameter Name="Name" />
       <asp:Parameter Name="Sex" />
       <asp:Parameter Name="ID" />
       <asp:Parameter Name="MaritalStauts" />
   </UpdateParameters>
</asp:SqlDataSource>

C# Code Behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 DataRowView dRowView = (DataRowView)e.Row.DataItem;
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
   if ((e.Row.RowState & DataControlRowState.Edit) > 0)
   {
     RadioButtonList rblGender = (RadioButtonList)e.Row.FindControl("rbGenderEdit");
     DropDownList ddlStatus = (DropDownList)e.Row.FindControl("ddlStatusEdit");
     rblGender.SelectedValue = dRowView[2].ToString();
     ddlStatus.SelectedValue = dRowView[3].ToString();
   }
 }
       
}
   
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
 RadioButtonList rblGender = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("rbGenderEdit");
 DropDownList ddlStatus = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlStatusEdit");
 SqlDataSource1.UpdateParameters["Sex"].DefaultValue = rblGender.SelectedValue;
 SqlDataSource1.UpdateParameters["MaritalStauts"].DefaultValue = ddlStatus.SelectedValue;
}
VB.NET Code Behind
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    Dim dRowView As DataRowView = DirectCast(e.Row.DataItem, DataRowView)
    If e.Row.RowType = DataControlRowType.DataRow Then
        If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
            Dim rblGender As RadioButtonList = DirectCast(e.Row.FindControl("rbGenderEdit"), RadioButtonList)
            Dim ddlStatus As DropDownList = DirectCast(e.Row.FindControl("ddlStatusEdit"), DropDownList)
            rblGender.SelectedValue = dRowView(2).ToString()
            ddlStatus.SelectedValue = dRowView(3).ToString()
        End If
        
    End If
End Sub

Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
    Dim rblGender As RadioButtonList = DirectCast(GridView1.Rows(e.RowIndex).FindControl("rbGenderEdit"), RadioButtonList)
    Dim ddlStatus As DropDownList = DirectCast(GridView1.Rows(e.RowIndex).FindControl("ddlStatusEdit"), DropDownList)
    SqlDataSource1.UpdateParameters("Sex").DefaultValue = rblGender.SelectedValue
    SqlDataSource1.UpdateParameters("MaritalStauts").DefaultValue = ddlStatus.SelectedValue
End Sub

Hope this helps.

Download sample code attached




Other posts in C# and ASP.NET
1.OpenFileDialog in winforms windows forms C# .NET VB.NET windows application
2.Find IP Address in ASP.NET Behind Proxy
3.Export GridView to Pdf using iTextSharp ASP.NET
4.Hide GridView Columns In ASP.NET C# VB.NET
5.Change Mode of DetailsView or FormView when Default Mode is Set to Insert in ASP.NET
6.Creating winforms AutoComplete TextBox using C# in Windows application
7.Disable copy paste cut and right click in textbox on aspx page using javascript

Continue Reading...

About Me

My Photo
amiT jaiN
Hi, I am amiT jaiN Software engineer working on C#.NET and ASP.NET technologies
View my complete profile

Comments

.NET Resources

Find More Articles


Subscribe To Feeds

Subscribe by E-mail

Enter your email address:

Delivered by FeedBurner


Subscribe in your favorite reader

This site is best viewed with || You may get errors in proper display of this site if using Internet explorer


C#.NET Articles and tutorials,ASP.NET Articles - blog by amiT jaiN