This program is in response to the assignment:
«Create a method named Sum()
that accepts any number of integer parameters and
displays their sum. Write a Main()
method that demonstrates that the Sum()
method works correctly when passed one, three, five, or an array of ten integers. Save the program as UsingSum.cs
.»
from Microsoft® Visual C#® 2008, An Introduction to Object-Oriented Programming, 3e, Joyce Farrell
My code in the «//step 1:» part is getting the CS0019 error, which states that it cannot be applied to operands of type bool
and int
.
I highly suspect there are also other problems with this code, but it’s a great improvement over what I had four hours ago…
using System;
public class UsingSum
{
public static void Main()
{
Sum();
}
public static void Sum()
{
// Step 1: Addition of one, three, five
bool q, r, s;
int firstTotal, n, o, p;
string k, l, m;
Console.Write("Type the number 1: ");
k = Console.ReadLine();
n = Convert.ToInt32(k);
q = Convert.ToBoolean(k);
Console.WriteLine();
if (q == 1)
Console.WriteLine("Input accepted.");
else if (!(q == 1))
{
Console.WriteLine("Error: You didn't type the number 1. Please try again.");
Console.Write("Type the number 1: ");
k = Console.ReadLine();
n = Convert.ToInt32(k);
q = Convert.ToBoolean(k);
}
}
Console.Write("Type the number 3: ");
l = Console.ReadLine();
r = Convert.ToBoolean(l);
o = Convert.ToInt32(l);
Console.WriteLine();
if (r <= 2 || r >= 4)
{
Console.WriteLine("Error: You didn't type the number 3. Please try again.");
Console.Write("Type the number 3: ");
l = Console.ReadLine();
r = Convert.ToBoolean(l);
o = Convert.ToInt32(l);
}
else
if (r = 3)
Console.WriteLine("Input accepted.");
Console.Write("Type the number 5: ");
m = Console.ReadLine();
p = Convert.ToInt32(m);
s = Convert.ToBoolean(m);
Console.WriteLine();
if (s <= 4 || s >= 6)
{
Console.WriteLine("Error: You didn't type the number 5. Please try again.");
Console.Write("Type the number 5: ");
m = Console.ReadLine();
p = Convert.ToInt32(m);
s = Convert.ToBoolean(m);
}
else
if (s = 5)
Console.WriteLine("Input accepted.");
firstTotal = n + o + p;
Console.WriteLine("{0} + {1} + {2} = {3}", n, o, p, firstTotal);
// Step 2: Entering integers for array[10]
int a, arrayTotal, b, c, d, e, f, g, h, i, j, unlimited;
Console.Write("Enter first integer for addition: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second integer for addition: ");
b = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter third integer for addition: ");
c = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter forth integer for addition: ");
d = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter fifth integer for addition: ");
e = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter sixth integer for addition: ");
f = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter seventh integer for addition: ");
g = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter eighth integer for addition: ");
h = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter ninth integer for addition: ");
i = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter tenth integer for addition: ");
j = Convert.ToInt32(Console.ReadLine());
arrayTotal = a + b + c + d + e + f + g + h + i +j;
Console.WriteLine("The total of {0} + {1} + {2} + {3} + {4} + {5} + {6} + {7} + {8} + {9} = {10}",
a, b, c, d, e, f, g, h, i, j, arrayTotal);
// Step 3: Unlimited array addition
int[] arrayTwo;
int total, y;
string ADD, x;
while(Console.Write("Enter an integer for addition, or type ADD to calculate the sum: "))
{
x = Console.ReadLine();
y = Convert.ToInt32(x);
if (x == ADD)
Console.WriteLine("Calculating the total sum");
}
for (y = 0; y < arrayTwo.Length; ++y)
{
total = arrayTwo[y] + arrayTwo[y];
++arrayTwo[y];
Console.WriteLine("========================");
Console.WriteLine("=/n= The total is: {0} =/n=", total);
Console.WriteLine("========================");
}
}
}
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Compiler Error CS0019 |
Compiler Error CS0019 |
07/20/2015 |
CS0019 |
CS0019 |
5a25be41-535b-4850-a230-9a385e01fd20 |
Compiler Error CS0019
Operator ‘operator’ cannot be applied to operands of type ‘type’ and ‘type’
A binary operator is applied to data types that do not support it. For example, you cannot use the || operator on strings, you cannot use +, -, <, or > operators on bool variables, and you cannot use the == operator with a struct
type unless the type explicitly overloads that operator.
You can overload an operator to make it support operands of certain types. For more information, see Operator overloading.
Example 1
In the following example, CS0019 is generated in three places because bool in C# is not convertible to int. CS0019 is also generated when the subtraction operator -
is applied to a string. The addition operator +
can be used with string operands because that operator is overloaded by the String
class to perform string concatenation.
static void Main() { bool result = true; if (result > 0) //CS0019 { // Do something. } int i = 1; // You cannot compare an integer and a boolean value. if (i == true) //CS0019 { //Do something... } string s = "Just try to subtract me."; float f = 100 - s; // CS0019 }
Example 2
In the following example, conditional logic must be specified outside the xref:System.Diagnostics.ConditionalAttribute. You can pass only one predefined symbol to the xref:System.Diagnostics.ConditionalAttribute.
The following sample generates CS0019:
// CS0019_a.cs // compile with: /target:library using System.Diagnostics; public class MyClass { [ConditionalAttribute("DEBUG" || "TRACE")] // CS0019 public void TestMethod() {} // OK [ConditionalAttribute("DEBUG"), ConditionalAttribute("TRACE")] public void TestMethod2() {} }
See also
- C# operators
C# Compiler Error Message
Operator ‘{0}’ cannot be applied to operands of type ‘{1}’ and ‘{2}’
Reason for the Error
You would usually get this error when you are using an operator that doesn’t support a specific data type. Below are some of the cases when you will receive this error.
- When you use bool and think, it works as integer.
public class Hello { public static void Main() { bool input = true; if (input > 0) // This Line results in cs0019 error. { // Do something. } } }
Error CS0019 Operator ‘>’ cannot be applied to operands of type ‘bool’ and ‘int’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 6 Active
- When you compare an int with boolean
namespace ClassLibrary { public class DeveloperPublish { public static void Main() { int input = 1; if (input == true) { } } } }
You will receive the below error.
Error CS0019 Operator ‘==’ cannot be applied to operands of type ‘int’ and ‘bool’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 8 Active
Some of the Other common scenarios that would result with this error includes
- When you use || operator on strings
- When you use +,- on boolean.
- When you use == with structs
Solution
To fix the error, ensure that you revisit the logic and ensure that the right operator is used for the operands in your .NET application.
- Remove From My Forums
-
Question
-
Can somebody please help me with this if statement? I keep on getting an error. I want the statement to say «cbCar.SelectedIndex = 0 AND rbNo.Checked» Here is the statement:
if (cbCar.SelectedIndex = 0 && rbNo.Checked)
{
dblTotal = 26695;
}This is the error I am getting:
Error CS0019 Operator ‘&&’ cannot be applied to operands of type ‘int’ and ‘bool’
Answers
-
Try using brackets to make absolutely certain the operands are being evaluated in the right order.
if ((cbCar.SelectedIndex == 0) && rbNo.Checked) { dblTotal = 26695; } // Or even, if you're getting really desperate... if ((cbCar.SelectedIndex == 0) && (rbNo.Checked == true)) { dblTotal = 26695; }
It shouldn’t be necessary, but I can’t think of anything else to try.
-
Marked as answer by
Monday, December 5, 2016 4:09 AM
-
Marked as answer by
Slavormund 0 / 0 / 0 Регистрация: 18.09.2020 Сообщений: 31 |
||||
1 |
||||
25.01.2021, 19:55. Показов 5052. Ответов 4 Метки нет (Все метки)
Я не понимаю в чем проблема,вроде подобное уже делал,но не могу понять Ошибка:
__________________
0 |
randok 612 / 392 / 187 Регистрация: 28.11.2019 Сообщений: 852 |
||||||||||||||||
25.01.2021, 19:58 |
2 |
|||||||||||||||
Решение
замените на
И вот тут будет ошибка
Если конечно Abs это не какой-то ваш метод.
1 |
1483 / 880 / 321 Регистрация: 17.05.2015 Сообщений: 3,351 |
|
25.01.2021, 20:01 |
3 |
if (((a = 1) && (b = 2)) = — оператор присваивания
1 |
0 / 0 / 0 Регистрация: 18.09.2020 Сообщений: 31 |
|
25.01.2021, 20:06 [ТС] |
4 |
с Abs нет ошибки, я использовал using static System.Math; чтобы не вызывать каждый раз класс Math (вроде правильно объяснил)
0 |
612 / 392 / 187 Регистрация: 28.11.2019 Сообщений: 852 |
|
25.01.2021, 20:13 |
5 |
чтобы не вызывать каждый раз класс Math Я понял мысль, но лучше так не делать, вносит сумятицу при чтении кода. Вот я не посмотрел на юзинги и сразу в глаза бросился этот Abs. В общем, уводит внимание от привычного написания метода.
0 |
Эта программа является ответом на задание:
«Создайте метод с именем Sum()
который принимает любое количество целочисленных параметров и отображает их сумму. Написать Main()
метод, демонстрирующий, что Sum()
работает правильно при передаче одного, трех, пяти или массива из десяти целых чисел. Сохраните программу как UsingSum.cs
.»
из Microsoft® Visual C #® 2008, Введение в объектно-ориентированное программирование, 3e, Джойс Фаррелл
Мой код в части «// шаг 1:» получает ошибку CS0019, в которой говорится, что ее нельзя применить к операндам типа bool
и int
.
Я очень подозреваю, что с этим кодом есть и другие проблемы, но это большое улучшение по сравнению с тем, что было у меня четыре часа назад …
using System;
public class UsingSum
{
public static void Main()
{
Sum();
}
public static void Sum()
{
// Step 1: Addition of one, three, five
bool q, r, s;
int firstTotal, n, o, p;
string k, l, m;
Console.Write("Type the number 1: ");
k = Console.ReadLine();
n = Convert.ToInt32(k);
q = Convert.ToBoolean(k);
Console.WriteLine();
if (q == 1)
Console.WriteLine("Input accepted.");
else if (!(q == 1))
{
Console.WriteLine("Error: You didn't type the number 1. Please try again.");
Console.Write("Type the number 1: ");
k = Console.ReadLine();
n = Convert.ToInt32(k);
q = Convert.ToBoolean(k);
}
}
Console.Write("Type the number 3: ");
l = Console.ReadLine();
r = Convert.ToBoolean(l);
o = Convert.ToInt32(l);
Console.WriteLine();
if (r <= 2 || r >= 4)
{
Console.WriteLine("Error: You didn't type the number 3. Please try again.");
Console.Write("Type the number 3: ");
l = Console.ReadLine();
r = Convert.ToBoolean(l);
o = Convert.ToInt32(l);
}
else
if (r = 3)
Console.WriteLine("Input accepted.");
Console.Write("Type the number 5: ");
m = Console.ReadLine();
p = Convert.ToInt32(m);
s = Convert.ToBoolean(m);
Console.WriteLine();
if (s <= 4 || s >= 6)
{
Console.WriteLine("Error: You didn't type the number 5. Please try again.");
Console.Write("Type the number 5: ");
m = Console.ReadLine();
p = Convert.ToInt32(m);
s = Convert.ToBoolean(m);
}
else
if (s = 5)
Console.WriteLine("Input accepted.");
firstTotal = n + o + p;
Console.WriteLine("{0} + {1} + {2} = {3}", n, o, p, firstTotal);
// Step 2: Entering integers for array[10]
int a, arrayTotal, b, c, d, e, f, g, h, i, j, unlimited;
Console.Write("Enter first integer for addition: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second integer for addition: ");
b = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter third integer for addition: ");
c = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter forth integer for addition: ");
d = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter fifth integer for addition: ");
e = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter sixth integer for addition: ");
f = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter seventh integer for addition: ");
g = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter eighth integer for addition: ");
h = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter ninth integer for addition: ");
i = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter tenth integer for addition: ");
j = Convert.ToInt32(Console.ReadLine());
arrayTotal = a + b + c + d + e + f + g + h + i +j;
Console.WriteLine("The total of {0} + {1} + {2} + {3} + {4} + {5} + {6} + {7} + {8} + {9} = {10}",
a, b, c, d, e, f, g, h, i, j, arrayTotal);
// Step 3: Unlimited array addition
int[] arrayTwo;
int total, y;
string ADD, x;
while(Console.Write("Enter an integer for addition, or type ADD to calculate the sum: "))
{
x = Console.ReadLine();
y = Convert.ToInt32(x);
if (x == ADD)
Console.WriteLine("Calculating the total sum");
}
for (y = 0; y < arrayTwo.Length; ++y)
{
total = arrayTwo[y] + arrayTwo[y];
++arrayTwo[y];
Console.WriteLine("========================");
Console.WriteLine("=/n= The total is: {0} =/n=", total);
Console.WriteLine("========================");
}
}
}
-
#1
Please Tell me if the Line 13 `if (Txt_AddUser_UserName_TextChanged(sender, e) == true)` is now a write way then how to write it.
//This part to add a user in database as a signup in Line 13 in the condition of if I tried to create a logic if Txt_AddUser_UserName_TextChanged(object sender, EventArgs e) this is true only than it sign up otherwise throws an error. Butt In this Line I came across this error, CS0019 Operator '==' cannot be applied to operands of type 'method group' and 'bool'
private void Btn_SignUp_Click(object sender, EventArgs e)
{
String Role = Combo_UserRole.Text;
String Name = Txt_AddUser_Name.Text;
String DOB = DatePicker_AddUser_DOB.Text;
Int64 Mobile = Int64.Parse(Txt_AddUser_MobileNo.Text);
String Email = Txt_AddUser_Email.Text;
String UserName = Txt_AddUser_UserName.Text;
String Password = Txt_AddUser_Password.Text;
try
{
if (Txt_AddUser_UserName_TextChanged(sender, e) == true) //Error is in this Line
{
Query = "insert into Users_Table (User_Role,User_Name,DOB,User_Mobile,User_Email,User_Username,User_Password) values('" + Role + "','" + Name + "','" + DOB + "','" + Mobile + "','" + Email + "','" + UserName + "','" + Password + "')";
SqlCommand cmd = new SqlCommand(Query, Conn.Connect);
Conn.OpenConnection();
int t = cmd.ExecuteNonQuery();
Conn.CloseConnection();
if (t > 0)
{
MessageBox.Show("Data Inserted Successfully!", "Success! Data Inserted", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Data is not Inserted! Try enter the data correctly", "Error! Data Not Inserted", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
}
public void Txt_AddUser_UserName_TextChanged(object sender, EventArgs e)
{
Query2 = "select * from Users_Table where User_Username='" + Txt_AddUser_UserName.Text + "'";
SqlDataAdapter QryCmd = new SqlDataAdapter(Query2, Conn.Connect);
DataTable dt = new DataTable();
QryCmd.Fill(dt);
if (dt.Rows.Count == 0)
{
PictureBox_Username_tick_cross.ImageLocation = @"C:UsersfarooOneDriveDesktopGraphin8-POSImagesyes.png"; //Tick Image to show Username is Available
}
else
{
PictureBox_Username_tick_cross.ImageLocation = @"C:UsersfarooOneDriveDesktopGraphin8-POSImagesno.png"; // Cross Image to Show Username already taken and is in the Database
}
}
-
J
jmcilhinney
- Sep 6, 2021
It’s kinda for me to tell you what you sound like because I’m the one who’s reading what you’re typing. What you intend it to sound like and what it actually sounds like aren’t necessarily the same thing, as evidenced by your first three posts. Thankfully, you did provide a decent description in your fourth post and now you’ve gone and repeated what I said was my understanding of what you wanted. I have already provided you with the solution. First you wouldn’t provide the explanation and now you won’t stop providing it. I have shown you how to get a value of type bool
that indicates whether the user name entered is new or not. You can then use that value to make decisions. I’ve shown you how to do…
-
#2
Maybe if you were actually explain what you’re trying to achieve there, rather than expecting us to work it out ourselves from code that doesn’t actually achieve it. Is it too much to expect that you actually explain your problem, rather than writing as few words as possible?
The line you highlighted makes no sense. Txt_AddUser_UserName_TextChanged
is, by the look of it, an event handler, which handles the TextChanged
event of a TextBox
named Txt_AddUser_UserName
. It’s return type is void
. Why exactly would you expect that to be equal to true
or to anything else for that matter?
-
#3
Maybe if you were actually explain what you’re trying to achieve there, rather than expecting us to work it out ourselves from code that doesn’t actually achieve it. Is it too much to expect that you actually explain your problem, rather than writing as few words as possible?
The line you highlighted makes no sense.
Txt_AddUser_UserName_TextChanged
is, by the look of it, an event handler, which handles theTextChanged
event of aTextBox
namedTxt_AddUser_UserName
. It’s return type isvoid
. Why exactly would you expect that to be equal totrue
or to anything else for that matter?
BTW I explained in comment part of the code, but as asked, Here I wanted to Signup a user only when in this Txt_AddUser_UserName_TextChanged this Event in line 36 is true then the Btn_SignUp_Click Event executes otherwise throws an error.
-
#4
BTW I explained in comment part of the code, but as asked, Here I wanted to Signup a user only when in this Txt_AddUser_UserName_TextChanged this Event in line 36 is true then the Btn_SignUp_Click Event executes otherwise throws an error.
Maybe if you were actually explain what you’re trying to achieve there, rather than expecting us to work it out ourselves from code that doesn’t actually achieve it. Is it too much to expect that you actually explain your problem, rather than writing as few words as possible?
The line you highlighted makes no sense.
Txt_AddUser_UserName_TextChanged
is, by the look of it, an event handler, which handles theTextChanged
event of aTextBox
namedTxt_AddUser_UserName
. It’s return type isvoid
. Why exactly would you expect that to be equal totrue
or to anything else for that matter?
I accept that I am doing it wrong that why I am on the forum to seek help in getting the idea on how to do that, What I am doing wrong as being a student and in learning stage I seek help of professionals to improve my skills.
-
#5
BTW I explained in comment part of the code, but as asked, Here I wanted to Signup a user only when in this Txt_AddUser_UserName_TextChanged this Event in line 36 is true then the Btn_SignUp_Click Event executes otherwise throws an error.
Firstly, don’t explain your problem in code comments. Code comments are for commenting the code. Explain your problem in the post.
Secondly, that isn’t an explanation anyway because, as I have already explained, this:
Txt_AddUser_UserName_TextChanged this Event in line 36 is true
is nonsense. That’s like saying that you only want to lie down if your leg is true. Please explain what you’re actually trying to achieve. Are you saying, without actually saying, that you want to perform an action only if the user has entered text into a particular TextBox
? If so, say that. If not, say what you are trying to do.
-
#6
I accept that I am doing it wrong that why I am on the forum to seek help in getting the idea on how to do that, What I am doing wrong as being a student and in learning stage I seek help of professionals to improve my skills.
The issue is not that you’re doing it wrong so much as you’re doing it wrong and not making any attempt to explain what it is that you’re doing. We shouldn’t have to work out what problem we ‘re trying to solve as well as solve it. You should be doing everything in your power to provide a FULL and CLEAR explanation of the problem, not dumping your code and assuming that we will immediately see what the purpose is and the correct way to achieve that purpose. That code is so nonsensical that there’s no indication of what it is supposed to actually do, so how can we tell you how to do it? If you’d like us to volunteer our time to help you, the least you can do is take the time to ensure we can do that without undue effort. We’re here because we want to help but we generally don’t want to be taken advantage of and that’s what it feels like when people try to get away with doing as little as possible to help us help them. All I’m asking for is for you to explain your problem, which isn’t really something that we should have to ask for.
-
#7
The issue is not that you’re doing it wrong so much as you’re doing it wrong and not making any attempt to explain what it is that you’re doing. We shouldn’t have to work out what problem we ‘re trying to solve as well as solve it. You should be doing everything in your power to provide a FULL and CLEAR explanation of the problem, not dumping your code and assuming that we will immediately see what the purpose is and the correct way to achieve that purpose. That code is so nonsensical that there’s no indication of what it is supposed to actually do, so how can we tell you how to do it? If you’d like us to volunteer our time to help you, the least you can do is take the time to ensure we can do that without undue effort. We’re here because we want to help but we generally don’t want to be taken advantage of and that’s what it feels like when people try to get away with doing as little as possible to help us help them. All I’m asking for is for you to explain your problem, which isn’t really something that we should have to ask for.
Ok I Got it I explain the scenario, There is a Form named Add User, and that add user form is connected to a database, Where after filling all the field comprises of combo date time picker and textboxes, When the user click on a signup button named Btn_SignUp
It need to first see if the username textbox named Txt_AddUser_UserName
is checked if the Username already exist in the database. If it is already in the database It will not signup and shows an error if it is a new username that a user typed in Txt_AddUser_UserName
only then the user will be succesfully signed up. for that vary reason I created a TextChanged
Event in which I shown Tick or Cross Image as a validation kind of thing that shows if the User already exists or not in the database. Then for the Btn_SignUp
I created a click event Btn_SignUp_Click
where I tried to say if the Txt_AddUser_UserName_TextChanged
is true then run the signup code.
Below is a Part where is just a simple it will insert a data in to database.
private void Btn_SignUp_Click(object sender, EventArgs e)
{
String Role = Combo_UserRole.Text;
String Name = Txt_AddUser_Name.Text;
String DOB = DatePicker_AddUser_DOB.Text;
Int64 Mobile = Int64.Parse(Txt_AddUser_MobileNo.Text);
String Email = Txt_AddUser_Email.Text;
String UserName = Txt_AddUser_UserName.Text;
String Password = Txt_AddUser_Password.Text;
try
{
Query = "insert into Users_Table (User_Role,User_Name,DOB,User_Mobile,User_Email,User_Username,User_Password) values('" + Role + "','" + Name + "','" + DOB + "','" + Mobile + "','" + Email + "','" + UserName + "','" + Password + "')";
SqlCommand cmd = new SqlCommand(Query, Conn.Connect);
Conn.OpenConnection();
int t = cmd.ExecuteNonQuery();
Conn.CloseConnection();
if (t > 0)
{
MessageBox.Show("Data Inserted Successfully!", "Success! Data Inserted", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Data is not Inserted! Try enter the data correctly", "Error! Data Not Inserted", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
}
Then this part below is for checking if the username is already in the database or not and on that basis it will show a tick name yes.png and cross names no.pnd in a picture box right beside the Username textbox
public void Txt_AddUser_UserName_TextChanged(object sender, EventArgs e)
{
Query2 = "select * from Users_Table where User_Username='" + Txt_AddUser_UserName.Text + "'";
SqlDataAdapter QryCmd = new SqlDataAdapter(Query2, Conn.Connect);
DataTable dt = new DataTable();
QryCmd.Fill(dt);
if (dt.Rows.Count == 0)
{
PictureBox_Username_tick_cross.ImageLocation = @"C:UsersfarooOneDriveDesktopGraphin8-POSImagesyes.png"; //Tick Image to show Username is Available
}
else
{
PictureBox_Username_tick_cross.ImageLocation = @"C:UsersfarooOneDriveDesktopGraphin8-POSImagesno.png"; // Cross Image to Show Username already taken and is in the Database
}
}
Now I wanted the above sign button click event Btn_SignUp_Click
to be only run when the Username Textbox TextChanged Event says the username is available and shows green tick as shown in the picture above. for that I made that nonsense mistake which I asked and seek help for how to do it was this below: to add a if condition if (Txt_AddUser_UserName_TextChanged(sender, e) == true)
in signup button click event Btn_SignUp_Click
part of code.
private void Btn_SignUp_Click(object sender, EventArgs e)
{
String Role = Combo_UserRole.Text;
String Name = Txt_AddUser_Name.Text;
String DOB = DatePicker_AddUser_DOB.Text;
Int64 Mobile = Int64.Parse(Txt_AddUser_MobileNo.Text);
String Email = Txt_AddUser_Email.Text;
String UserName = Txt_AddUser_UserName.Text;
String Password = Txt_AddUser_Password.Text;
try
{
if (Txt_AddUser_UserName_TextChanged(sender, e) == true)
{
Query = "insert into Users_Table (User_Role,User_Name,DOB,User_Mobile,User_Email,User_Username,User_Password) values('" + Role + "','" + Name + "','" + DOB + "','" + Mobile + "','" + Email + "','" + UserName + "','" + Password + "')";
SqlCommand cmd = new SqlCommand(Query, Conn.Connect);
Conn.OpenConnection();
int t = cmd.ExecuteNonQuery();
Conn.CloseConnection();
if (t > 0)
{
MessageBox.Show("Data Inserted Successfully!", "Success! Data Inserted", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Data is not Inserted! Try enter the data correctly", "Error! Data Not Inserted", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
}
-
#8
It sounds like what you’re saying is that what you care about is whether or not the Text
of a particular TextBox
contains an existing user name or not. In that case, declare a bool
that represents that:
private bool isUserNameNew = false;
You can then set that flag in your TextChanged
event handler:
var sql = "SELECT COUNT(*) FROM Users_Table WHERE User_Name = @User_Name";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("@User_Name", SqlDbType.VarChar, 50).Value = Txt_AddUser_UserName.Text;
connection.Open();
isUserNameNew = ((int)command.ExecuteScalar()) == 0;
}
and test it in your Click
event handler:
if (isUserNameNew)
{
// Create new user here.
}
Again, an event handler can’t «be true». Only a Boolean expression can be true, which means a field or property of type bool
, a method with a return type of bool
or some expression that evaluates to type bool
. A void
method can’t BE anything. It just DOES something.
-
#9
It sounds like what you’re saying is that what you care about is whether or not the
Text
of a particularTextBox
contains an existing user name or not. In that case, declare abool
that represents that:private bool isUserNameNew = false;
You can then set that flag in your
TextChanged
event handler:var sql = "SELECT COUNT(*) FROM Users_Table WHERE User_Name = @User_Name"; using (var connection = new SqlConnection(connectionString)) using (var command = new SqlCommand(sql, connection)) { command.Parameters.Add("@User_Name", SqlDbType.VarChar, 50).Value = Txt_AddUser_UserName.Text; connection.Open(); isUserNameNew = ((int)command.ExecuteScalar()) == 0; }
and test it in your
Click
event handler:if (isUserNameNew) { // Create new user here. }
Again, an event handler can’t «be true». Only a Boolean expression can be true, which means a field or property of type
bool
, a method with a return type ofbool
or some expression that evaluates to typebool
. Avoid
method can’t BE anything. It just DOES something.
What I Sound like that I Care about what user type in username textbox, Signup depends on Username textbox if the user typed a username is already in the database then clicking on a signup button will gives error and will not insert form data to database. What user will type defines the two images green tick and cross. If user types a username that already exists it will show red cross which means change username and if user types a new username that is not already exists in a database it will show a green tick and it will make a successful entry upon clicking a signup button.
-
#10
It’s kinda for me to tell you what you sound like because I’m the one who’s reading what you’re typing. What you intend it to sound like and what it actually sounds like aren’t necessarily the same thing, as evidenced by your first three posts. Thankfully, you did provide a decent description in your fourth post and now you’ve gone and repeated what I said was my understanding of what you wanted. I have already provided you with the solution. First you wouldn’t provide the explanation and now you won’t stop providing it. I have shown you how to get a value of type bool
that indicates whether the user name entered is new or not. You can then use that value to make decisions. I’ve shown you how to do that with an if
statement. You can also use an if...else
to decide which of two things to do, e.g. which of two images to display. Of course, that can be more streamlined:
PictureBox_Username_tick_cross.ImageLocation = Path.Combine(@"C:UsersfarooOneDriveDesktopGraphin8-POSImages",
isUserNameNew
? "yes.png"
: "no.png");
-
#11
It’s kinda for me to tell you what you sound like because I’m the one who’s reading what you’re typing. What you intend it to sound like and what it actually sounds like aren’t necessarily the same thing, as evidenced by your first three posts. Thankfully, you did provide a decent description in your fourth post and now you’ve gone and repeated what I said was my understanding of what you wanted. I have already provided you with the solution. First you wouldn’t provide the explanation and now you won’t stop providing it. I have shown you how to get a value of type
bool
that indicates whether the user name entered is new or not. You can then use that value to make decisions. I’ve shown you how to do that with anif
statement. You can also use anif...else
to decide which of two things to do, e.g. which of two images to display. Of course, that can be more streamlined:PictureBox_Username_tick_cross.ImageLocation = Path.Combine(@"C:UsersfarooOneDriveDesktopGraphin8-POSImages", isUserNameNew ? "yes.png" : "no.png");
Thank you Sir and sorry as being first time posting on a forum as a student didn’t knew much but today I learned next time when I will post a thread it will be well explained at a very first Thank you for your Patience Regards
-
#12
All’s well that ends well. As long as you learn from your mistakes, that’s all we can really ask. Glad you got it working.