Эта ошибка означает, что у Вас несовместимые типа в сравнении.
То есть, около какого-то знака слева и справа стоят bool и double.
В Вашем, конкретном случае, в этой конструкции: (End.X< Vector.X <Begin.X)
, компилятор сначала сравнивает End.X< Vector.X
, пускай будет 5.4 < 7.4, и получает true, затем берёт это значение и сравнивает с Begin.X
то есть true < 12.2
, вот он и ругается, мол не могу сравнить фиолетовый цвет с креслом, а вы спрашиваете у него, что из них больше?
Решение Вашей проблемы заключается в понимании типов переменных, конструкций языка, в общем почитайте литературу, пройдите онлайн уроки, чтобы изучить азы.
Также, есть 2 решения:
-
не очень хорошее:
Вместо этой строкиif ((( End.X< Vector.X <Begin.X)||( Begin.X< Vector.X < End.X))&&(c==d))
Вставить эту:
if (((( End.X< Vector.X) && (Vector.X <Begin.X))||(( Begin.X< Vector.X ) && (Vector.X < End.X)))&&(c==d))
-
Лучше:
Во-первых, можно удалить лишние скобки, студия их выделяет слабым серым, тогда их можно стереть без угрозы логике.
Также, называйте локальные переменные с маленькой буквы, меньше ошибок, понятнее, что вы обращаетесь к объекту, а не к статическому классу:То есть, преобразуем Ваш код вот так:
public static bool IsVectorInSegment(Vector vector, Vector end, Vector begin) { double c = (vector.X - begin.X) / (end.X - begin.X); double d = (vector.Y - begin.Y) / (end.Y - begin.Y); if (((end.X < vector.X < begin.X) || (begin.X < vector.X < end.X)) && (c == d)) return true; else return false; }
Во-вторых, эту проверку
c == d
можно вынести вверх, чтобы проверки стали проще и понятнее, ведь если она не выполнится, то мы не получим true, никогда, то есть убрали ещё пару скобок, сбивающих с толку:public static bool IsVectorInSegment(Vector vector, Vector end, Vector begin) { double c = (vector.X - begin.X) / (end.X - begin.X); double d = (vector.Y - begin.Y) / (end.Y - begin.Y); if (c != d) return false; if ((end.X < vector.X < begin.X) || (begin.X < vector.X < end.X)) return true; else return false; }
Далее, исправляем, Вашу, досадную ошибку:
public static bool IsVectorInSegment(Vector vector, Vector end, Vector begin) { double c = (vector.X - begin.X) / (end.X - begin.X); double d = (vector.Y - begin.Y) / (end.Y - begin.Y); if (c != d) return false; if (((end.X < vector.X) && (vector.X < begin.X)) || ((begin.X < vector.X) && (vector.X < end.X))) return true; else return false; }
Далее проведем последнее преобразование, дам другой пример (для понимания), попроще:
if (b < c) return true; else return false;
Компилятор сравнивает b и c, получая, например true, дальше проверяет, true == true?, значит надо вернуть true, можно же сразу, без проверки возвращать полученное значение сравнения, то есть:
return b < c;
Ну, и вишенка на тортике, уберем лишний if, и в конечном итоге, получим:
public static bool IsVectorInSegment(Vector vector, Vector end, Vector begin) { double c = (vector.X - begin.X) / (end.X - begin.X); double d = (vector.Y - begin.Y) / (end.Y - begin.Y); if (c != d) return false; return ((end.X < vector.X) && (vector.X < begin.X)) || ((begin.X < vector.X) && (vector.X < end.X)); }
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 |
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
-
User31568 posted
Hi,
How to avoid:
Error CS0019: Operator ‘==’ cannot be applied to operands of type ‘Task’ and ‘bool’ (CS0019)
In below code?
public partial class AboutMerchant : ContentView { public AboutMerchant() { InitializeComponent(); if (!Application.Current.Properties.ContainsKey("ZeeraCustomerID")) { App.Current.MainPage = new NavigationPage(new ZeeraSignin()); } else { // indicatorLoading.IsRunning = true; if (!Application.Current.Properties.ContainsKey("ZeeraMerchantNumber")) { App.Current.MainPage.DisplayAlert("Error", "You must select a merchant first.", "OK"); Application.Current.MainPage.Navigation.PopAsync(); return; } GetMerchantDetails Merchant = new GetMerchantDetails(); if (Merchant.MerchantDetails(Convert.ToString(Application.Current.Properties["ZeeraMerchantNumber"])) == true) { // await DisplayAlert("Scanned Barcode", "EXISTS", "OK"); // await Navigation.PushAsync(new ZeeraCategory()); // this.Title = Convert.ToString(Application.Current.Properties["ZeeraMerchantName"]); var htmlSource = new HtmlWebViewSource(); htmlSource.Html = Convert.ToString(Application.Current.Properties["ZeeraMerchantProfile"]); lblProfile.Source = htmlSource; loadingProfile.IsVisible = false; lblProfile.IsVisible = true; // GetCategory(); } else { App.Current.MainPage.DisplayAlert("Error", "Unable to find merchant details.!nCode: " + Convert.ToString(Application.Current.Properties["ZeeraMerchantNumber"]), "OK"); } } } }
My GetMerchantDetails is a Class:
using System; using System.Threading.Tasks; using Xamarin.Forms; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Text.RegularExpressions; using System.Net; using System.Text; namespace Zeera { public class GetMerchantDetails { public async Task<bool> MerchantDetails(string merchant_number) { var client = new HttpClient(); client.BaseAddress = new Uri("https://www.domain.com/ws/get_merchant_details.php?merchant=" + merchant_number); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync("https://www.domain.com/ws/get_merchant_details.php?merchant=" + merchant_number); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); dynamic merchantdata = JsonConvert.DeserializeObject(data); if (merchantdata.ToString() == "False") { return false; } else { App.Current.Properties.Remove("ZeeraMerchantNumber"); App.Current.Properties.Remove("ZeeraMerchantGuid"); App.Current.Properties.Remove("ZeeraMerchantName"); App.Current.Properties.Remove("ZeeraMerchantProfile"); App.Current.Properties.Remove("ZeeraMerchantCountry"); App.Current.Properties.Remove("ZeeraMerchantEmail"); App.Current.Properties.Remove("ZeeraMerchantCurrency"); App.Current.Properties.Remove("ZeeraMerchantActive"); App.Current.Properties.Remove("ZeeraMerchantBlocked"); App.Current.Properties.Add("ZeeraMerchantNumber", merchantdata[0].merchant_number); App.Current.Properties.Add("ZeeraMerchantGuid", merchantdata[0].merchant_guid); App.Current.Properties.Add("ZeeraMerchantName", merchantdata[0].merchant_name); App.Current.Properties.Add("ZeeraMerchantProfile", merchantdata[0].merchant_profile); App.Current.Properties.Add("ZeeraMerchantCountry", merchantdata[0].country_code); App.Current.Properties.Add("ZeeraMerchantEmail", merchantdata[0].email_address); App.Current.Properties.Add("ZeeraMerchantCurrency", merchantdata[0].base_currency); App.Current.Properties.Add("ZeeraMerchantActive", merchantdata[0].is_active); App.Current.Properties.Add("ZeeraMerchantBlocked", merchantdata[0].is_blocked); await App.Current.SavePropertiesAsync(); return true; } } return false; } } }
Kindly help..
Thanks,
Jassim
Answers
-
User89714 posted
@JassimRahma said:
but how to do that if I don’t have the OnAppearing in the ContentView?Your AboutMerchant view will be displayed as a result of being contained within the UI of a page. Expose methods in your AboutMerchant object, and have your page code-behind call those methods. If you want something to happen to your AboutMerchant object when the page’s OnAppearing method is called, override the page’s OnAppearing method and have your override call the methods in your AboutMerchant object. There are other ways of doing this (events, messaging etc), but start with that.
As mentioned before, read up on async/await (this is not the first thread in which you have asked about async/await-related stuff), rename your classes to have nouns for names, rename your methods to have verbs for names. Append «Async» to the end of the name of any method that returns Task or Task < T >, ensure your code builds without warnings (not by disabling the warnings), and read up on object-oriented design. If you have access to Xamarin.University, do the async/await class and any OO classes. If you don’t currently have Xamarin.University access, sign up for a month.
-
Marked as answer by
Thursday, June 3, 2021 12:00 AM
-
Marked as answer by
Эта программа является ответом на задание:
«Создайте метод с именем 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("========================");
}
}
}
private static object[] GetEnumLookupData<TEnum>() where TEnum: Enum { var data = Enum.GetValues(typeof(TEnum)) .OfType<TEnum>() .Where(e => e != default(TEnum)) .Select(e => new {Id = e, Name = e.ToString()}) .ToArray(); return data; }
This does not compile, but returns a error:
CS0019: Operator ‘!=’ cannot be applied to operands of type ‘TEnum’ and ‘TEnum’
What am I missing here? Isn’t it clear that TEnum
is a value type?
The funniest thing is that if I omit (TEnum)
in default(TEnum)
, so it is now e != default
it compiles, but default
generates porbably just a null
because I see 0 value in created EF Core migration. WTF?!
I tried to use EqualityComparer<TEnum>.Default.Equals(...)
and it kinda worked, however, EF Core 2.1 has a bug: migrations with seeding of data with emun as primary key are unstable. This bug is fixed only in EF Core 2.2 preview.
So I changed to int
and …
private static object[] GetEnumLookupData<TEnum>() where TEnum: struct, Enum { var comparer = EqualityComparer<TEnum>.Default; var data = Enum.GetValues(typeof(TEnum)) .OfType<TEnum>() .Where(e => !comparer.Equals(e, default)) .Select(e => new {Id = (int)e, Name = e.ToString()}) .ToArray(); return data; }
CS0030 Cannot convert type ‘TEnum’ to ‘int’
-
#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.