Friday, May 30, 2014

Enable a button on check box checked without page refresh

In this tutorial I will show you how to enable a button on checking of a check box without using any update panel.  This is i found when I wanted to enable a register button in an registration form using update panel and the Css of the button was not working when it is disable.

So lets create a new project. And add a new check box and a button into a new web form.


<asp:CheckBox ID="chkTermsCondition" runat="server" Text="Check now"/></a>
                        
<asp:Button ID="btnRegister" runat="server" Text="Register" 
onclick="btnRegister_Click" class="contact-button" />

Now in the head section add a java script code to do the action.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>
<script  type="text/javascript" >
    $(function () {
        var $btn = $(":submit[id$=btnRegister]");
        var $chk = $(":input:CheckBox[id$=chkTermsCondition]");
        // check on page load
        checkChecked($chk);
        $chk.click(function () {
            checkChecked($chk);
        });
        function checkChecked(chkBox) {
            if ($chk.is(':checked')) {
                $btn.removeAttr('disabled');
            }
            else {
                $btn.attr('disabled', 'disabled')
            }
        }
    });
</script>

Add Jquery plugin to your project or add Google, Jquery online plugin. And now run the project and test. Enjoy...  :)

Add Custom Controls in your ASP.NET Project

This article is about to discuss about the adding custom controls in  ASP.NET project. So what is a Custom control. Its a server control add you can create and add to any other project you want like C K Editor, AJAX Control Toolkit, Telerik, Dev Express etc.

So, to do this you need to create a new Server Control.


Now in this project you will find a class called ServerControl1.cs with code.
Now out mission is to do some action like say if in any other project in a textbox if we write "A" it will return "OK" else it will return "Not OK".

So copy the code follow here and paste into your RenderContents method.


protected override void RenderContents(HtmlTextWriter output)
{
    if (this.Text == "A")
   {
       output.Write("Its OK ---done by Arkadeep\n");
   }
   else
   {
        output.Write("Not OK ---done by Arkadeep\n");
   }      
}

Now build your project and get the .dll file of your project.

Now in another project add a new web form and add a new textbox and button.
On that project add the reference of your server control project.

Now add a register in the web form.


<%@ Register Assembly="ServerControl1" Namespace="ServerControl1" TagPrefix="ccs" %>
 
 Now add this code,


<ccs:ServerControl1 runat="server" ID="a1" Visible="false"></ccs:ServerControl1>

This is your control which you have created in your server control project.

Now in the button_click event write the code.


a1.Text = TextBox1.Text;
a1.Visible = true;

In this way you call your server control to execute. Now run your program to execute and test.

Download the full source code here.

Wednesday, May 28, 2014

Create an invisible password in Windows Application using C#

To day in this tutorial I will show you how to make an textbox in password mode without changing its TextMode property to Password.

I make this more simple by explaining the output of this program,

As an output there will be a textbox for inputing your password. But it will not show any charecter that will be written in the textbox, ie. invisible.

Create a new project and add a new form with a textbox, label & a button. Now on the TextChange event of the textbox write the code.


 label1.Text = label1.Text + textBox1.Text;
 textBox1.Text = "";

Make sure your label's  visible property if false.

Now in the button click event write down the code.

 label1.Text = "Your password : " + label1.Text;
 label1.Visible = true;

Now test your application.
Download the full source code here.

Thursday, May 22, 2014

Create random password in ASP.NET C#

In this tutorial I will show you how to make a random generate password in C#. You can apply it either in web application(ASP.NET) or in windows application.

Create a new project and add a web form or a win form as per your project. And then add a button. On the Button_Click() write the following code.


PasswordGenerator obj_p = new PasswordGenerator();
string new_password = obj_p.Generate();

Now you have to create a new class named PasswordGenerator and create a new method Generate.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace <Project_Name>
{
    public class PasswordGenerator
    {
        public PasswordGenerator() { }
 
        /// <summary>
        /// Password generator method
        /// </summary>
        /// <returns></returns>
        public  string Generate()
        {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var stringChars = new char[8];
            var random = new Random();
 
            for (int i = 0; i < stringChars.Length; i++)
            {
                stringChars[i] = chars[random.Next(chars.Length)];
            }
            var finalString = new String(stringChars);
            return finalString.ToString();
        }
    }
}

Now run the project and get the new password in the string new_password.

Happy coading :)

Wednesday, May 21, 2014

How to show alert box within UpdatePanel

Showing javascript alert box within update panel is some time very much problematic.
So here is the right way to show that.

Within a button click or any event coming from update panel write the following code to show the alert box

ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", "alert('<Your message>');", true);

Try this and enjoy

Get Identity after inserting into database in Ms. SQL Server

Suppose we have a table named tblUser with coloumn name
Id int auto increment primary key
Name nvarchar(255)
Email nvarchhar(255)

Now after inserting a value into tblUser an Id will automatic generate as Id. Now how will you retrieve that Id. Very simple.

After inserting code place the bellow code

SELECT @@IDENTITY

This one will return you the Id of the inserted row.

How to bind a DataGridView in a Windows project C#

Here I will show you how to bind a DataGridView in a windows application with a DataSet and SQLDataSource.

First  create a new windows project and add a new form. After that select a DataGridView and drag and drop into the form.


Now choose a new DataSource against the DataGridView.

Select New DataSource and click on the "Add Project Data Source".


Select the Database to proceed.



Now select the DataSet to continue.


Select the ConnectionString and click on the Next button.


Now after that choose the table name which one you want to display. You can choose multiple tables or views.


After that click on the Finish button to complete the process. Now in the bottom of the project you can see there is a DataSet named tblMessage. Open that and remove the columns that you don't want to display.


Now in the View Code section you can see in the Form_Load a new line of code is added. This one is binding the DataGdridView with the DataSet.

Now run the project and you will see in the output your database's table in the DataGridView.


Tuesday, May 20, 2014

Use Google Captcha in your ASP.NET Project in C#

Using captcha in your site making your site much better secure against hackers and their scripts. So in this article I will show you how to use Google recaptcha in your asp.net project.

First download the ReCaptcha.dll and add as a reference in your project. You can download this from here. Before starting this you need to register yourself to get a public & private key of your Google apps.

Now add the register code in your aspx page.


 <%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

And now add the following code in your aspx code, where you want to place your captcha.


<asp:Label Visible="false" ID="lblResult" runat="server" />
 
<recaptcha:recaptchacontrol id="recaptcha" runat="server" publickey="<Your public key>"
privatekey="<Your private key>" Theme="clean" />

In the code behind on a button click add the the code..


protected void btnSubmit_Click(object sender, EventArgs e)
{
      recaptcha.Validate();
      if(Page.IsValid && recaptcha.IsValid)
      {
           lblResult.Text = "You Got It!";
           lblResult.ForeColor = Drawing.Color.Green;
      }
      else
      {
           lblResult.Text = "Incorrect";
           lblResult.ForeColor = Drawing.Color.Red;
      }     
}

Your captcha is ready. Run the project and have fun.

Output :

Download the source code here.


Saturday, May 17, 2014

How to convert a string into array in c#

Many times its required to convert a string into an array. In this tutorial I will show how to convert a string into an array.

First take a textbox names TextBox1 and a button to convert it into array. Also take a label to show the result.

On the button click event write the following code..


private void button1_Click_1(object sender, EventArgs e)
{
    char []name ;
    int i = 0;
    int count = 0;
    /* Converting string into array */
    name = textBox1.Text.ToArray();   

    /* Using for loop */
    for (i = 0; i < name.Length;i++ )
    {
        label1.Text = label1.Text + Convert.ToString(name[i]);
    }  

    /* Using foreach loop */
    foreach (char a in name)
    {
         label1.Content = label1.Content + Convert.ToString(name[i]);
    }
}

Thursday, May 15, 2014

Insert Data using WCF Into Database in ASP.NET C#

In this article I will show you how to insert data into database using Windows Communication Foundation(W.C.F.). 

For that first you need to create a WCF Service Application.


Now to insert data into database you need to get help of two things.


  • OperationContract (Add services operation)
  • DataConntract (add type to services operation)
Now in the IService1.cs create your own method named InsertData(UserData user)


[OperationContract]
string InsertUserDetails(UserData user);

Now add the UserData class with its members  at IService1.cs


public class UserData
    {
        string password = string.Empty;
        string country = string.Empty;
        string email = string.Empty;
 
        [DataMember]
        public string Password
        {
            get { return password; }
            set { password = value; }
        }
        [DataMember]
        public string Country
        {
            get { return country; }
            set { country = value; }
        }
        [DataMember]
        public string Email
        {
            get { return email; }
            set { email = value; }
        }
    }

Now add the following code in the Service1.svc


public string InsertUserDetails(UserData userInfo)
        {
            string Message;
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=WCF_Demo;Trusted_Connection=true");
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into RegistrationTable(Password,Country,Email) values(@Password,@Country,@Email)", con);
            cmd.Parameters.AddWithValue("@Password", userInfo.Password);
            cmd.Parameters.AddWithValue("@Country", userInfo.Country);
            cmd.Parameters.AddWithValue("@Email", userInfo.Email);
            int result = cmd.ExecuteNonQuery();
            if (result == 1)
            {
                Message ="successful.";
            }
            else
            {
                Message = "Sorry Unsuccessful.";
            }
            con.Close();
            return Message;
        }

Now run the Service1.svc of the project. and will get an url in the browser.


Now create another project(Website) and add a new webform.


Now add a web reference to the project by right clicking on the project name in solution explorer.


And after adding this reference you will find that in your solution explorer.


Now add some textbox and a button to make a registration form. Something looking like this one.


Now in the code behind add the code following.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WCF_Insert.ServiceReference1;
 
namespace WCF_Insert
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        ServiceReference1.Service1Client objServiceClientobjService = new ServiceReference1.Service1Client();
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            UserDetails userInfo = new UserDetails();
            userInfo.Password = TextBoxPassword.Text;
            userInfo.Country = TextBoxCountry.Text;
            userInfo.Email = TextBoxEmail.Text;
            string result = objServiceClientobjService.InsertUserDetails(userInfo);
            LabelMessage.Text = result;
        }
    }
}

Before closing the application create a table named RegistrationTable with coloumns of..


CREATE TABLE [dbo].[RegistrationTable]
(
      [Password] [varchar](20) NOT NULL,
      [Country] [varchar](100) NOT NULL,
      [Email] [varchar](200) NOT NULL
)

Now its over. Run your project and enjoy the WCF.

Tuesday, May 13, 2014

Loading a .TXT file into a Label using C# in ASP.NET

Some times its very important to get and show data from an external file like .txt file. So in this example I will show you how to get the data of a .txt file in a label or a text box in ASP.NET using C#.

Create a new project and add a web form. In the App_Data folder create a txt file and put some data into it. We will get the value of from that txt file.

On the page load event of your web form write the following code.


if (!this.IsPostBack)
{
    using (StreamReader stRead = 
               new StreamReader(Server.MapPath("~/App_Data/file.txt")))
    {
        int i = 0;
        string name = string.Empty;
        string valueFromtoEnd = string.Empty;
 
        while (!stRead.EndOfStream)
        {
            if (i > 2 && i <= 4)
            {
                valueFromtoEnd += stRead.ReadLine();
            }
            else
            {
                Label1.Text = Label1.Text + stRead.ReadLine() + "<br />";
            }
            i++;
            if (i > 4)
            {
                break;
            }
        }
    }
}


It will show the text as in the .txt file.
If you want to show it in a text box just change the label into a text box.

Download the full source code here.

Get HTML Drop Down List value in code behind C#

Few days ago I stuck into a problem , I need to get the value of from a HTML drop down list in my c# code behind page. So I started searching and found the solution.  Very simple solution indeed. Just a single line code to end the problem.

Suppose the drop down list code is


<select name="cars">
  <option value="volvo">Volvo XC90</option>
  <option value="saab">Saab 95</option>
  <option value="mercedes">Mercedes SLK</option>
  <option value="audi">Audi TT</option>
</select>

And a ASP button to get the value..


<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Now on the C# page write the bellow code.


var car = Request["cars"];
Response.Write(car.ToString());

If you are using ASP Drop Down List then the code will be little bit different.


<asp:DropDownList ID="DropDownList1" runat="server">
   <asp:ListItem>Item1</asp:ListItem>
   <asp:ListItem>Item2</asp:ListItem>
   <asp:ListItem>Item3</asp:ListItem>
</asp:DropDownList>

And on button click..


Response.Write(DropDownList1.SelectedValue.ToString());
Response.Write(DropDownList1.SelectedItem.Text.ToString());

Now enjoy the code..

Monday, May 5, 2014

Add User Control Tool dynamically in ASP.NET C#

In previous post I have wrote about UserControlTool. In this post I will show how to add the UserControlTool dynamically in an aspx page.

First add the folder as a namespace into the .CS page.

Suppose project name is "asx_add" and in the folder "tool" all the user control tools are presented.

So add the namespace.

using asx_add.tools;

Now add the line bellow to add the control tool.
private Header h1;
 
h1 = (Header)LoadControl("~/tools/Header.ascx");
this.Controls.Add(h1);
PlaceHolder1.Controls.Add(h1);

Now run the code and you will found that the user control is added to your web page.

Download the full source code here.

Popular Posts

Pageviews