Feed on
Posts
Comments

C# Windows Validation by ErrorProvider

 

In ASP.Net 2.0 we use different Validation controls from Toolbox for validations (Just Drag & Drop, No need of writing code in C#). But in Case of C# windows application this feature is not available so we use Error Provider control to do any type of validation.

 

 

For example:-

 

If we take a Employee data…

  1. Name (Text)
  2. Age (Integer)
  3. Salary (Double)

 

Form looks like

 

 

In ADD button click you need to write the following code.

 

private void ADD_Click(object sender, EventArgs e)

{

  if (is_validate())

  {

    errorProvider1.Clear();

    // Write Coding to add into database

    MessageBox.Show(“Data Successfully Added”);

  }

}

 

private bool is_validate()

{

  bool no_error = true;

  if (txtname.Text == string.Empty)

  {

    errorProvider1.SetError(txtname, “Text Missing”);

    no_error = false;

  }

  else

  {

    // Clear all Error Messages

    try

    {

      int i = Convert.ToInt32(txtage.Text);

    }

    catch

    {

      errorProvider1.Clear(); // Clear all Error Messages

      errorProvider1.SetError(txtage, “Enter Valid Age”);

      return false;

    }

    try

    {

      double j = Convert.ToDouble(txtsalary.Text);

    }

    catch

    {

      errorProvider1.Clear(); // Clear all Error Messages

      errorProvider1.SetError(txtsalary, “Enter Valid Salary”);

      return false;

    }

   }

   return no_error;

}

 

Here one Error Provider Control can be used for multiple fields.

 

That’s it. It’s all done. Its Very Simple isn’t it??

                      

 

ASP.Net & C# Create HTML Controls

Dynamically

 

It is very easy to create HTML controls before running a Web Page. Just Drag and Drop from ToolBox or write HTML code or ASP code for that Web Page (.aspx). But people think that generating HTML controls during runtime is difficult. But it’s quite easy.

There are many methods of generating controls during runtime.

Here is the one.

 

First thing is that you need to add a Panel by drag and drop it from the toolbox.

 

After that you need to write the C# code in Page Load event or button event as follows :

 

Panel1.Controls.Add(new LiteralControl(“<table><tr>”));

Panel1.Controls.Add(new LiteralControl(“<td colspan=2 align=center    valign=middle >”));

Panel1.Controls.Add(new LiteralControl(“<table><tr><td>”));

Panel1.Controls.Add(new LiteralControl(“<input id=’Text1′ type=’text’ value=’Ganesh Mohan’ />”));

Panel1.Controls.Add(new LiteralControl(“</td><td>”));

Panel1.Controls.Add(new LiteralControl(“<a href=http://ganeshmohan.wordpress.com>”));

Panel1.Controls.Add(new LiteralControl(“Hi This is Ganesh”));

Panel1.Controls.Add(new LiteralControl(“</a>”));

Panel1.Controls.Add(new LiteralControl(“</td></tr></table>”));

 

 

That’s it. Its all Done. Its So Simple isn’t it!

ASP.Net & C# Login Page

 

Whenever we want to start any project the first thing we think about the User Roles and Login. Generally there will be mainly two User Roles

a)    Administrator User

b)    Client User

 

In VS 2005 its very simple to design a Login Page. Because there is no need of bringing textboxes, labels & buttons together to design a login page and writing code in that button click event. The VS 2005 have a readymade tool in its toolbox called as “Login”.

You just have to Drag & Drop that on your .aspx page

 

 

After drag & drop you can change that to your desired design by clicking on Auto Format

 

 

Then we need to go to the ‘Properties’ of that Login Control and click on Events.

There we can see a event called Authenticate, Double click on it.

 

 

 

Once that is done. You have to write the C# code in that event

 

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.Data.SqlClient;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)

    {

        try

        {

            string uname = Login1.UserName.Trim(); //Get the username from the control

            string password = Login1.Password.Trim(); //get the Password from the control

            bool flag = AuthenticateUser(uname, password);

            if (flag == true)

            {

                e.Authenticated = true;

                Login1.DestinationPageUrl = “After_Login.aspx”;

            }

            else

                e.Authenticated = false;

        }

        catch (Exception)

        {

            e.Authenticated = false;

        }

    }

 

    private bool AuthenticateUser(string uname, string password)

    {

       bool bflag = false;

 string connString = “Server=localhost;Database=mproi;Uid=sa;Pwd=;”;

string strSQL = “select * from tbl_user where user_name =’” +   uname + “‘ AND user_password =’” + password + “‘”;

       DataSet userDS = new DataSet();

       SqlConnection m_conn;

       SqlDataAdapter m_dataAdapter;

       SqlCommand m_Command;

       try

       {

           m_conn = new SqlConnection(connString);

           m_conn.Open();

           m_dataAdapter = new SqlDataAdapter(strSQL, m_conn);

           m_dataAdapter.Fill(userDS);

           m_conn.Close();

       }

       catch (Exception ex)

       {

           userDS = null;

       }

 

       if (userDS != null)

       {

           if(userDS.Tables[0].Rows.Count > 0)

             bflag = true;

       }

       return bflag;

    }

}

 

 

That’s it. Its all Done. Your Login Page is ready. Its So Simple isn’t it!

ASP.Net, C# and Javascript Count Down Timer

 

ASP.Net Code

While displaying a count down timer on your Web Page you need to do following things :

On the web page you need to add 7 controls.

In that one is HTML Text box which displays the count down time

<input type=”text” readonly =”true” size=”8″ id=”counter” style=”text-align:center; font-size:x-large; font-weight:bold; color:Red;” />

 and rest of six are hidden fields in which three of them are HTML controls and other are ASP controls looks loke this

 

<input type=”hidden” size=”8″ id=”HidHours” value=”<%=HidH.Value%>“/>

<input type=”hidden” size=”8″ id=”HidMinutes” value=”<%=HidM.Value%>“/>

<input type=”hidden” size=”8″ id=”HidSeconds” value=”<%=HidS.Value%>“/>

<asp:HiddenField ID=”HidH” runat=”server” Value=”0″ />

<asp:HiddenField ID=”HidM” runat=”server” Value=”0″ />

<asp:HiddenField ID=”HidS” runat=”server” Value=”0″ />

 Now you need to write the main JavaScript part which displays this count down time

<script>

var hours=document.getElementById(‘HidHours’).value;

var minutes=document.getElementById(‘HidMinutes’).value;

var seconds=document.getElementById(‘HidSeconds’).value;

function

display()

{

if (seconds<=0)

{

if ((hours==0)&&(minutes==0))

seconds=0;

else

{

seconds=60;

minutes-=1;

}

}

if (minutes<=0)

{

if ((hours<0)&&(minutes<0))

{

hours = minutes = seconds = 0;

}

else

{

if ((hours==0)&&(minutes==0))

hours=minutes=0;

if ((hours>0)&&(minutes<0))

{

minutes=59;

hours-=1;

}

}

}

if ((minutes<=-1)||(hours<=-1))

{

if (hours<=-1)

{

minutes=0;

hours+=1;

}

else

minutes-=1;

seconds=0;

minutes+=1;

}

else

if (seconds>0)

seconds-=1;

document.getElementById(‘counter’).value=hours+“:”+minutes+“:”+seconds;

setTimeout(“display()”,1000);

}

display();

</script>

 

The Main Concept Over Here is the Time from where the count down begins that time you need to pass into ASP Hidden fields whose id are HidH, HidM and HidS which defines hours, minutes and seconds respectively. Now these values are passed to HTML Hidden Controls whose id are  HidHours, HidMinutes and HidSeconds since the values of ASP controls value’s can not be passed directly to JavaScript code. We kept HTML controls as bridge between ASP controls Value’s and JavaScript. and Now Javascript function display() is called recursively until hours, minutes and seconds becomes zero. Once it is zero you can redirect to any page you want

C# Code

TimeSpan ts;

HidH.Value = Convert.ToString(ts.Hours);

HidM.Value = Convert.ToString(ts.Minutes);

HidS.Value = Convert.ToString(ts.Seconds);

 click here : http://groups.google.co.in/group/dotnethelp2008/web/count-down-timer-asp-net-javascript-and-c?hl=en&msg=ns