hi,

i am new in C# , i have 2 text boxes in which the user will enter the department and name,
1- I want the application to retrict the user to only enter letters not numbers . This is my following code:

public string Directorates_Insert(string Directorate_Name, string Directorate_Head)
{
SqlConnection con = new SqlConnection();
SqlCommand com = new SqlCommand();

try
{

con.ConnectionString = conString;
con.Open();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "Directorates_Insert";


com.Parameters.AddWithValue("@Directorate_Name", Directorate_Name);
com.Parameters.AddWithValue("@Directorate_Head", Directorate_Head);
com.ExecuteNonQuery();

return "0";

}
catch(Exception ex)
{ 
return ex.Message;
}
finally
{
con.Close();

// da.Dispose();
com.Dispose();
con.Dispose();
}

}
}

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

}


protected void btn_save_Click(object sender, EventArgs e)
{
btn_save.Enabled = false;

lookups insert = new lookups();
string result = insert.Directorates_Insert(txt_DirName.Text.Trim(), txt_DirHead.Text.Trim());
if (result == "0")
{
lbl_msg.ForeColor = System.Drawing.Color.Blue;
lbl_msg.Text = "Successful";
}
else
{
lbl_msg.ForeColor = System.Drawing.Color.Red;
lbl_msg.Text = result;
}
btn_save.Enabled = true;
}

2- How can i put a grid view to view the records he entered?

public DataSet Directorates_GetAll()
{
SqlConnection con = new SqlConnection();
SqlCommand com = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
try
{
con.ConnectionString = conString;
con.Open();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "Directorates_GetAll";
da.SelectCommand = com;


com.Parameters.AddWithValue("@ID", DBNull.Value);
com.ExecuteNonQuery();
da.Fill(ds);
return ds;

}
catch
{
return ds;
}
finally
{
con.Close();
ds.Dispose();
da.Dispose();
com.Dispose();
con.Dispose();
}

}

Thank you

Recommended Answers

All 15 Replies

To allow letters only subscribe to KeyPress event of textbox, and put this code inside (dont copy/paste the event, just the code inside of it):

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            //allows backspace key
            if (e.KeyChar != '\b')
            {
                //allows just letter keys
                e.Handled = !char.IsLetter(e.KeyChar);  
            }
        }

In which part of my code shall i add it?

ok solved, thankx , i just need the solution for the second part of my question
How can i view the records entered in the database?

public DataSet Directorates_GetAll()
    {
        SqlConnection con = new SqlConnection();
        SqlCommand com = new SqlCommand();
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();
        try
        {
            con.ConnectionString = conString;
            con.Open();
            com.Connection = con;
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = "Directorates_GetAll";
            da.SelectCommand = com;

            
            com.Parameters.AddWithValue("@ID", DBNull.Value);
            com.ExecuteNonQuery();
            da.Fill(ds);
            return ds;

        }
        catch
        {
            return ds;
        }
        finally
        {
            con.Close();
            ds.Dispose();
            da.Dispose();
            com.Dispose();
            con.Dispose();
        }

    }

simple, write a select query, fill the dataset, bind the dataset to the grid view and display.
you can also use masking to restrict the user to type any kind of required characters.

Can you please send me a sample of the code

In which part of my code shall i add it?

??

Subscribe to the textBox_KeyPress event, this will rise every time user will type into textBox. While typing it will not allow to enter other chars then letters (letters only, so no special chars, or numbers).

i added this to the KeyPress but its not working

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;

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

    }


    protected void btn_save_Click(object sender, EventArgs e)
    {
        btn_save.Enabled = false;

        lookups insert = new lookups();
        string result = insert.PMEWDirectorates_Insert(txt_DirName.Text.Trim(), txt_DirHead.Text.Trim());
        if (result == "0")
        {
            lbl_msg.ForeColor = System.Drawing.Color.Blue;
            lbl_msg.Text = "Successful";
        }
        else
        {
            lbl_msg.ForeColor = System.Drawing.Color.Red;
            lbl_msg.Text = result;
        }
        btn_save.Enabled = true;
    }



    private void txt_DirName_KeyPress(object sender, KeyPressEventArgs e)
    {
         if (e.KeyChar != '\b')
            {               
             //allows just letter keys    
             e.Handled = !char.IsLetter(e.KeyChar); 
         }
    }


   
}

You didnt just copy/paste my code?
For the event you have to SUBSCRIVE, not only copy it.
YOu can do:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;

public partial class Parts_PMEWDirectorate : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
       this.txt_DirName.KeyPress += new KeyPressEventHandler(txt_DirName_KeyPress); //ADD THIS LINE OF CODE - this is subscribing!!
    }


    protected void btn_save_Click(object sender, EventArgs e)
    {
        btn_save.Enabled = false;

        lookups insert = new lookups();
        string result = insert.PMEWDirectorates_Insert(txt_DirName.Text.Trim(), txt_DirHead.Text.Trim());
        if (result == "0")
        {
            lbl_msg.ForeColor = System.Drawing.Color.Blue;
            lbl_msg.Text = "Successful";
        }
        else
        {
            lbl_msg.ForeColor = System.Drawing.Color.Red;
            lbl_msg.Text = result;
        }
        btn_save.Enabled = true;
    }



    private void txt_DirName_KeyPress(object sender, KeyPressEventArgs e)
    {
         if (e.KeyChar != '\b')
            {               
             //allows just letter keys    
             e.Handled = !char.IsLetter(e.KeyChar); 
         }
    }   
}

i'm getting an error in this line of code

this.txt_DirName.KeyPress += new KeyPressEventHandler(txt_DirName_KeyPress);

i'm getting :
using System.Web.UI.WebControls.TextBox does not contain a definition for 'KeyPress'

hmm, sorry, your project is a .net applicaiton, not a windows app.
So you need an event for web app. There is no KeyPress event. There ar only these events.

You could use TextChecked event.
Just did this code for you, and it works fine.

bool bJump;
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (!bJump)
            {
                if (textBox1.Text.Length > 0)
                {
                    char lastChar = textBox1.Text.Substring(textBox1.Text.Length - 1)[0];
                    if (!char.IsLetter(lastChar))
                    {
                        bJump = true;
                        textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1, 1);
                        textBox1.SelectionStart = textBox1.Text.Length;
                        textBox1.SelectionLength = 0;
                    }
                }
            }
            else
                bJump = false;
        }

But dont forget to subscribe to TextChanged event in Form_Load event (like I showed you for other KeyPress event).

Thank you Mitja, i tried the code but it will still accept numbers

goto txt_DirName properties -> click on events -> u ll get KeyPress event -> double click on it, n then add the code the inside the method.

since u have copy pasted the code, u r getting an error.

sorry, i didnt notice that there was another page. (couldnt delete this)

They way I do this is I create a new void like so:

public void StripAlphabetCharacters(TextBox input)
{
	Regex rx = new Regex("[^0-9.]"); //Put Characters to Allow in the ""
	if ((rx.IsMatch(input.Text))) {
		int startPosition = input.SelectionStart - 1;
		input.Text = rx.Replace(input.Text, "");
		input.SelectionStart = startPosition;
	}
}

And then you add the following code to the TextBox_TextChanged Event:

StripAlphabetCharacters(textBox1);

You will also need to add this code to your class:

using System.Text.RegularExpressions;

This is the final code I created while solving your problem:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //This is What My Final Test Project Code Looks Like
        }

        public void StripAlphabetCharacters(TextBox input)
        {
            Regex rx = new Regex("[^0-9.]");
            if ((rx.IsMatch(input.Text)))
            {
                int startPosition = input.SelectionStart - 1;
                input.Text = rx.Replace(input.Text, "");
                input.SelectionStart = startPosition;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            StripAlphabetCharacters(textBox1);
        }
    }
}

Thank you all

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.