How to use string.IsNullOrEmpty in Textbox? - c#

I'm trying to display null value only if the textbox is empty. In my case even if i'm giving input in the textbox, it won't detect as null value. Kindly help me to solve my error please.
protected void AnyTextBox_TextChanged(object sender, EventArgs e)
{
if ((string.IsNullOrEmpty(TextBox1.Text)))
{
TBResult1.Text = "N/A";
}
else
{
TBResult1.Text = TextBox1.ToString();
}
<asp:TextBox ID="TextBox1" OnTextChanged="AnyTextBox_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
<asp:TextBox ID="TBResult1" OnTextChanged="AnyTextBox_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>

From documentation:
String.IsNullOrEmpty Method
Indicates whether the specified string is null or an Empty string.
Example:
string s1 = "abcd"; // is neither null nor empty.
string s2 = ""; // is null or empty
string s3 = null; // is null or empty
string.IsNullOrWhiteSpace(s1); // returns false
string.IsNullOrWhiteSpace(s2); // returns true
string.IsNullOrWhiteSpace(s3); // returns true
Also, you can do this:
if (string.IsNullOrEmpty(s1)) {
Message.Show("The string s1 is null or empty.");
}
In your code:
if ((string.IsNullOrEmpty(TextBox1.Text)))
{
// The TextBox1 does NOT contain text
TBResult1.Text = "N/A";
}
else
{
// The TextBox1 DOES contain text
// TBResult1.Text = TextBox1.ToString();
// Use .Text instead of ToString();
TBResult1.Text = TextBox1.Text;
}

Replace
TBResult1.Text = TextBox1.ToString();
with
TBResult1.Text = TextBox1.Text;

Try this:
if(string.IsNullOrWhiteSpace(this.textBox1.Text))
{
MessageBox.Show("TextBox is empty");
}

It should be like this, You have missed TextBox1.Text in the else part
protected void AnyTextBox_TextChanged(object sender, EventArgs e)
{
if ((string.IsNullOrEmpty(TextBox1.Text)))
{
TBResult1.Text = "N/A";
}
else
{
TBResult1.Text = TextBox1.Text.ToString();
}
}

Check you conditions like this.i use this one and it works fine.
if(TextBox1.Text.Trim().Length > 0)
{
//Perform your logic here
}
Otherwise you have to check these two functions
if (string.IsNullOrEmpty(TextBox1.Text.Trim()) || string.IsNullOrWhiteSpace(TextBox1.Text.Trim()))
{
}

Related

ASP.NET Formview Textbox value- Object reference not set to an instance of an object

I would like to know whether or not this control is null once the page loads before I perform another operation. At the moment it just throws the object reference error.
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.ReadOnly)
{
string cname =
(this.FormView1.FindControl("companyname") as
System.Web.UI.WebControls.TextBox).Text;
if (cname == null)
{
}
else{
}
}
}
check for textbox first (make sure thats the ID youre looking up), something like,
TextBox compName = (Textbox)this.FormView1.FindControl("companyname");
string cName = "";
if(compName != null)
{
cName = compName.Text;
}
else
{
// textbox not found! do something?
}

How can I store only one object into array in WPF?

Why doesn't the below code store one object into the array? I can't find my mistake. If the array has one object already, it should display another message.
Here is the C# code. I guess the XAML code isn't necessary. Perhaps my mistake is with NULL?
TraderInfos[] bossArray = new TraderInfos[1];
public Reset_Register()
{
InitializeComponent();
}
private void CheckPassword(object sender, RoutedEventArgs e)
{
if (bossArray != null)
{
if (SecurtyQuestionMother.Text == securityQ_mother_textbox.Text && SecurityQuestionSchool.Text == securityQ_school_texbox.Text)
{
foreach (var item in bossArray)
{
PasswordApears.Text = $"Your password is: {item.Password}";
}
}
else
{
PasswordApears.Text = "You've not found it";
}
}
else
{
MessageBox.Show("There isnt being any data stored yet");
}
}
private void SafeTheEntries(object sender, RoutedEventArgs e)
{
if (bossArray == null)
{
TraderInfos boss = new TraderInfos()
{
First_Name = first_name_textbox.Text,
Last_Name = last_name_textbox.Text,
Company_Name = company_name_textbox.Text,
Phonenumber = phonenumber_textbox.Text,
Password = passwordText.Text,
SecurityQuestionMother = securityQ_mother_textbox.Text,
SecurityQuestionSchool = securityQ_school_texbox.Text
};
bossArray[0] = boss;
MessageBox.Show($"dear {boss.First_Name}!\nYour data has been saved!");
}
else
{
MessageBox.Show("You can't enter more one entry!");
}
}
Your code creates the array at the top and, because of that, your array will not be null. The bossArray[0] should be equal to null, not bossArray.
So check
if (bossArray[0] != null)
or
if (bossArray[0] == null)

How to validate textbox value while user enters and display error message?

So, I have to code for a method that validates whether the string that saves name contains alphabets only, no numbers. The validation of textbox values should apply when the user enters by textchanged event before submitting the form and display an error message of red color on the label. My code works but the problem is when I enter a numeric number in text box, the label displays error which stays even when I delete the text box value and enter the alphabetic string.
I have declared a method which assign error string to label, and is called if regular expression does not match with the text box input, during text changed event.
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
Regex pattern = new Regex("/^[A-Za-z]+$/");
string name = _Name.Text;
if (pattern.IsMatch(name))
{
Calculate_Salary.Enabled = true;
label4.Text = "";
}
else
{
Validator();
}
}
Just clear the textbox before you validate:
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = "";
Regex pattern = new Regex("/^[A-Za-z]+$/");
string name = _Name.Text;
if (pattern.IsMatch(name))
{
Calculate_Salary.Enabled = true;
}
else
{
Validator();
}
}
Your Regex comparison is wrong try this code:
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = "";
string name = _Name.Text;
if (Regex.IsMatch(name, #"^[a-zA-Z]+$"))
Calculate_Salary.Enabled = true;
else
Validator();
}
I changed the validation code. It seems to work now.
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = string.Empty;
string name = _Name.Text;
if (Regex.IsMatch(_Name.Text, "^[a-zA-Z]+$") || _Name.Text=="")
{
Calculate_Salary.Enabled = true;
}
else
{
Calculate_Salary.Enabled = false;
label4.Text = Validator();
}
}

List Box Selected.value throwing null exception

Populated list box like this:
if (ds != null)
{
ListPreviousRecords.Items.Clear();
ListPreviousRecords.DataSource = ds;
ListPreviousRecords.DataTextField = "Date";
ListPreviousRecords.DataValueField = "ID";
ListPreviousRecords.DataBind();
}
Get selected value:
protected void ListPreviousRecords_OnSelectedIndexChanged(object sender, EventArgs e)
{
if(ListPreviousRecords.SelectedItem.Value != "")
{
int mySelectedValue = int.Parse(ListPreviousRecords.SelectedItem.Value);// throwing null exception
loadPreviousDetails(mySelectedValue);
}
}
You can add this code in order to ensure that not null value is entered
if(!string.IsNullOrEmpty(ListPreviousRecords.SelectedItem.Value ))
{
...
}
And Ensure that AutoPostBack="true" is set on your control
link : http://msdn.microsoft.com/fr-fr/library/system.string.isnullorempty.aspx
Change:
if(ListPreviousRecords.SelectedItem.Value != "")
To:
if (!string.IsNullOrEmpty(ListPreviousRecords.SelectedItem))
Use ListPreviousRecords.SelectedValue.
if (!string.IsNullOrWhiteSpace(ListPreviousRecords.SelectedValue)) {
// ...
}

how to get selected column value or name from datagrid in asp.net using c#

My code is like this : Now I have now idea how to get column name of selected row
protected void gv_imageslist_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string status;
string sts;
int result;
lblerror2.Text = "";
//((label)gv.Rows.FindControl("lbl1")).Text;
string str = gv_imageslist.c
if (str == "Status")
{
status = ((Label)gv_imageslist.Rows[e.RowIndex].FindControl("lbl_Status")).Text;
Gm.Gallery_Id = Convert.ToInt32(gv_imageslist.DataKeys[e.RowIndex].Value.ToString());
if (status == "True")
{
Gm.Is_Active = false;
}
else
{
Gm.Is_Active = true;
}
result = Gm.Change_Image_Status();
if (result == 1)
{
Build_ImageGalleryList();
}
else
{
lblerror2.Visible = true;
lblerror2.Text = "Unable to Change Status !";
}
}
else
//------For Checking of cover pic
{
sts = ((Label)gv_imageslist.Rows[e.RowIndex].FindControl("lbl_Cover")).Text;
Gm.Gallery_Id = Convert.ToInt32(gv_imageslist.DataKeys[e.RowIndex].Value.ToString());
string sp = ((Label)gv_imageslist.Rows[e.RowIndex].FindControl("lbl_category_Id")).Text;
Gm.Category_Id = Convert.ToInt32 (sp);
if (sts == "False")
{
Gm.Is_Cover = true;
}
else
{
Gm.Is_Cover = false;
}
result = Gm.Change_Gallery_Cover();
if (result == 1)
{
Build_ImageGalleryList();
}
else
{
lblerror2.Visible = true;
lblerror2.Text = "Unable To Change Cover Pic !!";
}
}
}
Try this code snippet;
gv.HeaderRow.Cells[i].Text
Why not create an object of the selected row and work with it from there?
i.e.
var selectedRow = (TYPE)gridViewName.GetFocusedRow();
You could then use the selectedRow object and call any properties belonging to it
i.e. var name = selectedRow.Name
It can be possible through DataKeyNames and Normal method also
1) 'e' as Commandargument
int index = Convert.ToInt32(e.CommandArgument);
string request = gvRequests.Rows[index].Cells[4].Text.ToString();
2) GridViewRow selectedRow = gvRequests.Rows[index];
string Id = gvRequests.DataKeys[index].Value.ToString().Trim();
string headerText=gvProductList.HeaderRow.Cells[1].Text;
protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
LinkButton lnk = (LinkButton) e.Row.FindControl("lnk");
Label lblName= (Label) e.Row.FindControl("lblName");
lnk.Attributes.Add("onclick", "getValue(" + lblName.ClientID + ");"
}
}... You can try this... method in your own way
Enjoy... ..

Categories