Category Archives: C#

Traverse / Loop through all form controls in asp.net

This post explains that how to traverse (loop through) all form controls in asp.net page.

foreach (System.Web.UI.Control ctrl in this.form1.Controls)
{
//here your code
}

Further if you want to get the state or data or manipulate the control, use the below code:
Here I am checking that at least one DropDownList item is selected out of all DropDownLists in the current webform.

bool isSelected = false;

foreach (System.Web.UI.Control ctrl in this.form1.Controls)
{

if (ctrl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
{
DropDownList ddl = (DropDownList)ctrl;

if (ddl.SelectedItem.Text != "")
{
isSelected = true;
break;
}
}

}

if (isSelected == true)
{
Response.Write("selected");
}
else
{
Response.Write("none selected");
}


Username Regex Validation

While accepting values from user you must validate the values because wrong values (like XSS attacks) can cause harm to your database and website.

Regex Code:
The Regular Expression below validates the username format.
^[a-zA-Z0-9_]{5,20}$

Scope:
So while creating a new user for a website you can validate the username string with the following business logic:
1) User name must be between 5 to 20 characters.
2) User name can have lowercase and uppercase characters.
3) User name can be alpha-numeric.
4) No special character allowed.

As you can see this is a very basic code to evaluate simple username for your website.
Implementation:

Asp.net HTML code:

<asp:TextBox ID=”txtRegex” runat=”server”></asp:TextBox>
<asp:Button ID=”btnValidate” runat=”server” Text=”Validate value” OnClick=”btnValidate_Click” />
<asp:Label ID=”lblResultRegex” runat=”server” Text=””></asp:Label></div>

Asp.net Code Behind:

using System.Text.RegularExpressions;

protected void btnValidate_Click(object sender, EventArgs e)
{
    if (Regex.IsMatch(txtRegex.Text, @”^[a-zA-Z0-9_]{3,16}$”) == true)
    {
        lblResultRegex.Text = “username ok”;
    }
    else
    {
        lblResultRegex.Text = “username invalid”;
    }
}

Now just run the application an verify the results.

To download a visual studio source code visit http://dotnetcoderoom.blogspot.com/2008/10/username-regex-validation.html


Read & Write to System Registry data, keys using C#

In this post i am going to explain that how to access the System Registry and how to read and write data to registry.

Step 1: First you need to import the below namespaces:
using Microsoft.Win32;

Step 2: Now create an object of Registry class:
RegistryKey regkey;

Step 3: Now access the registry and get the value of a key

regkey = Registry.CurrentUser.CreateSubKey(@”Software\Microsoft\FTP”);

if (regkey.GetValue(“Use PASV”) == null)
{
txtValue.Text = “No Value Specified”;
}

else
{
txtValue.Text = regkey.GetValue(“Use PASV”).ToString();
}

The above code gets the value of the “Use PASV” key from the
Registry\CurrentUser\Software\Microsoft\FTP path.

Step 4: Set the key value
regkey.SetValue(“Use PASV”, txtValue.Text);


Operator + cannot be applied to operands of type string and method group, C# error

Cause

This error comes up when you tries to append two strings with the “+” sign. As the + sign in C# is a arithmetical operator so you cannot use this too append two string type values. To use “+” the values or variables must be if numeric type.

As C# uses doesn’t supports implicit typecasting, for string concatenation use “&” sign.
Example

string varTest = “”;
string str1 = “abc”;
int str2=21;

varTest = str1 + str2;

The above stqatmet will cause in error stating “Operator + cannot be applied to operands of type string and method group“. Because we are trying to add a string variable in a numeric variable.

To remove the error you must convert all the numeric (integer) datatype or variables to string.

varTest = str1 & str2.ToString();

The output of the above code will be abc21

Conclusion
We must convert all values to a uniform datatype before storing them into a variable.


Send e-mail in ASp.Net 2.0 and onwards in C#

The following code example can be used to send email using Asp.Net in 2.0 and higher versions version.

The Namespace of email class is changed to System.Net.Mail from System.Web.Mail.

Import the System.Net.Mail Namespace
using System.Net.Mail;

Code:

MailMessage mail = new MailMessage();
mail.From = new MailAddress(“info@yourDomain.com”,”Alert”);
mail.To.Add(“you@yourdomain.com”);
mail.Subject = “mail test”;
mail.IsBodyHtml = true;
mail.Body = “Your message here”;
SmtpClient smtp = new SmtpClient(“mail.yourdomain.com”);
smtp.Credentials = new System.Net.NetworkCredential(“info@yourdomain.com”,”password of this info”);
smtp.Send(mail);

Note:
The email address specified in the “FROM” field must be valid and it need to be of your domain.
In the SmtpServer the domain name must be same as of your domain on which website is hosted.

For complete source code visit
http://dotnetcoderoom.blogspot.com


Send e-mail using Asp.Net 1.1

The following code example can be used to send email using Asp.Net in 1.1 version.

First import Web.Mail namespace.
using System.Web.Mail;

Now add this code to your button click event:

MailMessage mail = new MailMessage();

String msgText = string.Empty;
msgText = “Message here, you can also use Html tags for Rich Text Formatting.<br>Hi.”;

mail.To = “you@yourdomain.com”;
mail.CC = “anyEmailAddress, its optional”;
mail.Bcc = “anyEmailAddress, its optional”;
mail.From = @”””Ajay”” <info@yourdomain.com>”;
//mail.From = “info@yourdomain.com”;
mail.Subject = “Mail test”;
mail.BodyFormat = MailFormat.Html;
mail.Body = msgText;
SmtpMail.SmtpServer = “mail.yourdomain.com”;

SmtpMail.Send(mail);

Note:

The email address specified in the “FROM” field must be valid and it need to be of your domain.
In the SmtpServer the domain name must be same as of your domain on which website is hosted.


ASp.Net 2.0 GridView Delete Button Confirmation pop-up

While using GridView in asp.net pages wants to confirm the deletion form user. To do this we can take him to another page having GUI to confirm and then delete the record on that page.

Instead of doing so much hardwork you can achieve this on the same page with a little bit of extra code.

Workaround

Add a client alert script to the delete button of every row.
In the delete event of GridView delete the record.

Code

==================================================
Page’s Aspx Design File Begins
==================================================
<asp:GridView ID=”gvFaq” runat=”server” AutoGenerateColumns=”False” CellPadding=”4″
ForeColor=”#333333″ GridLines=”None” OnRowDataBound=”gvFaq_RowDataBound” OnRowDeleting=”gvFaq_RowDeleting”>
<FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />
<Columns>
<asp:BoundField DataField=”slno” HeaderText=”Sl No.” />
<asp:BoundField DataField=”cHeading” HeaderText=”Question” />
<asp:BoundField DataField=”cPosition” HeaderText=”Position” />
<asp:CommandField HeaderText=”Manage” ShowSelectButton=”True” />
<asp:CommandField HeaderText=”Delete” ShowDeleteButton=”True” />
</Columns>
<PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
<HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<EditRowStyle BackColor=”#999999″ />
<AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
</asp:GridView>
==================================================
Page’s Aspx Design File Ends
==================================================

Database Design FIle

==================================================
Code Behind File Begins
==================================================
1) Import Namespaces
using System.Data.SqlClient;

2) Declare global variables which will be used in page
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = “your database connection string goes here”‘;
String sql = string.Empty;

3) Page Load event
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
fillGridView();
}
}

4) GridView filling method
private void fillGridView()
{

try
{
myConnection = new SqlConnection(connStr);
sql = “select * from tblFaq order by slno desc”;

da = new SqlDataAdapter(sql, myConnection);
ds.Clear();
da.Fill(ds, “tblFaq”);

gvFaq.DataSource = ds.Tables[0];
Page.DataBind();

}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

5) In the RowDataBound event add a java script event to the delete cell.
protected void gvFaq_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[4].Attributes.Add(“onClick”, “return confirm(‘Are you sure you want to delete the record?’);”);
}
}

6) Handle the RowDeleting event to delete the record of current row.

protected void gvFaq_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
myConnection = new SqlConnection(connStr);
myConnection.Open();
sql = “delete from tblFaq where slno = ” + Convert.ToInt32(gvFaq.Rows[e.RowIndex].Cells[0].Text);
SqlCommand oldcom = new SqlCommand(sql, myConnection);
oldcom.ExecuteNonQuery();
myConnection.Close();
fillGridView();
Response.Write(“Record Deleted”);
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}

==================================================
Code Behind File Ends
==================================================
The output will look like this

For Source Code visit http://dotnetcoderoom.blogspot.com/2008/08/aspnet-20-gridview-delete-button.html