Click here to Skip to main content
15,903,175 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
See more:
hi,
i wan to split words from textbox,

means..i search users by firstname or lastname
.

and my coding for pass textbox valu as firstname , lastname in property is here..
it show me error if i left the space
means
i enterd
manish dalwadi
in textbox
its complete work
but if i entered only
manish it show me error

C#
string data = txtsearchusers.Text;
        string[] s1 = data.Split();

        string a = s1[0].ToString();
        string b = s1[1].ToString();
        clsregisterinfo.FirstName = a.ToString();
        clsregisterinfo.LastName = b.ToString();
Posted

Check th econdition and assign b value;

C#
if (s1 != null && s1.Count() > 1)
            {
string b = s1[1].ToString();
clsregisterinfo.LastName = b.ToString();
            }
 
Share this answer
 
Hi,
Why you are splitting the text box value.If u want to search users means u can do it in sql query it self. like

C#
string search = "select * from tblUsers where name like'%" + txtUsername.Text + "'%";

Then bind the value where ever u want to show.
 
Share this answer
 
You would have encountered IndexOutofRangeException, right? That is because s1[1] did not exist.
Suggest use 2 textboxes, one for firstname and another for last name. Not only does it eliminate unnecessary code, but also make your intention clearer to the users as well.
 
Share this answer
 
v2
Try like this

C#
string data = txtsearchusers.Text;
        string[] s1 = data.Split();
        string fName = null, sName = null;
        fName = s1[0].ToString();
        clsregisterinfo.FirstName = fName;
        if (s1.Length == 2)
        {
            sName = s1[1].ToString();
            clsregisterinfo.LastName = sName;
        }


In the Query you can check the condition as
if Second name is null then ignore the condition(checking second name) in SQL Query. else check with the first name only....
 
Share this answer
 
In this case s[0] will have value.

But it is good programming practice that before getting value from any object first check the value existence of the object.

In this case you have to write

if(s[1]!= null)
{
<!--Assign value -->
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900