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)
Related
currently i am working a one project and i got this type of error.
i excuted the procedure and in debugging mode prcedure pass the data to entity file but when i go back to aspx page so that time i got this null exception.
how can i resolve.
any one help me?.
UserDAL file
this is a prcedure
public UserENT PR_IP_User_LoginUser(SqlInt32 UserID)
{
using (SqlConnection objconn = new SqlConnection(ConnectionString))
{
objconn.Open();
using (SqlCommand objcmd = objconn.CreateCommand())
{
try
{
#region Prepaed Command
objcmd.CommandType = CommandType.StoredProcedure;
objcmd.CommandText = "PR_IP_User_LoginUser";
objcmd.Parameters.AddWithValue("#UserID", UserID);
#endregion
UserENT entuser = new UserENT();
#region Read and set controls
using (SqlDataReader objSDR = objcmd.ExecuteReader())
{
while (objSDR.Read())
{
if (!objSDR["User_Name"].Equals(DBNull.Value))
{
entuser.User_Name = Convert.ToString(objSDR["User_Name"].ToString().Trim());
}
if (!objSDR["Password"].Equals(DBNull.Value))
{
entuser.Password = Convert.ToString(objSDR["Password"].ToString().Trim());
}
if (!objSDR["User_ID"].Equals(DBNull.Value))
{
entuser.User_ID = Convert.ToInt32(objSDR["User_ID"]);
}
if (!objSDR["ContactNo"].Equals(DBNull.Value))
{
entuser.ContactNo = Convert.ToString(objSDR["ContactNo"]);
}
if (!objSDR["Email_ID"].Equals(DBNull.Value))
{
entuser.Email_ID = Convert.ToString(objSDR["Email_ID"]);
}
if (!objSDR["Is_Admin"].Equals(DBNull.Value))
{
entuser.Is_Admin = Convert.ToBoolean(objSDR["Is_Admin"]);
}
}
return entuser;
}
#endregion
}
catch (Exception e)
{
Message = e.InnerException.Message;
return null;
}
finally
{
objconn.Close();
}
}
}
}
#endregion
on client side or can say aspx page
on button click event
protected void btnLogin_Click(object sender, EventArgs e)
{
#region Server Side Validation
String strerr = "";
if (txtusername.Text.Trim() == "")
{
strerr += "Enter UserName";
}
if (txtpassword.Text.Trim() == "")
{
strerr += "Enter Password";
}
if (strerr != "")
{
lblMessage.EnableViewState = true;
lblMessage.Text = strerr;
}
#endregion
#region Gather Data
SqlString Username, userpass;
if (txtusername.Text.Trim() != "")
{
Username = txtusername.Text.Trim();
}
if (txtpassword.Text.Trim() != "")
{
userpass = txtusername.Text.Trim();
}
#endregion
UserBAL baluser = new UserBAL();
UserENT entuser = new UserENT();
SqlInt32 UserID_Res;
SqlString User_name_res, User_Password_res;
SqlInt32 userid = Convert.ToInt32(txtuserid.Text.Trim());
if (Request.QueryString["User_ID"] == null)
{
if (baluser.Login(userid) != null)
{
User_name_res = entuser.User_Name.Value.ToString().Trim();
UserID_Res = Convert.ToInt32(entuser.User_ID.Value);
User_Password_res = entuser.Password.Value.ToString().Trim();
if (User_name_res == txtusername.Text.Trim() || User_Password_res == txtpassword.Text.Trim())
{
Response.Redirect("AddSubject.aspx");
}
else
{
Response.Redirect("AddTopic.aspx");
}
}
}
#endregion
The C# code associated with a ".aspx" page (or code behind) is executed on the server side.
I assume that UserBAL.Login() function returns the user's data once logged in. It may be necessary to get the returned object.
On button click event :
protected void btnLogin_Click(object sender, EventArgs e)
{
...
UserENT entuser = baluser.Login(userid);
if (entuser != null)
{
...
Thanks every one who help to solve my error. now i resolve my error.
i Just pass the data to procure and check the data in procedure and return
Boolean value.
Thanks Again :)
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?
}
I am currently making a fitness class booking system for some study I am doing so please bare with me.
I have done most of the code but I am having this strange issue with my 2nd radio button for selecting what class you want.
I have set up my code so a message box appears if the Member ID you have entered is already registered to the fitness class you have selected. For my RadioButton1 (rbCardioClass) and RadioButton2 (rbPilatesClass), the error message box works great and works as it should. But my RadioButton2 (rbSpinClass) will make the error message box appear everytime, even if the MemberID is not associated to the 'Spin Class'.
I have tried different uses of if statements, different radio buttons etc but can't seem to get it to work the way I want.
If I go to my servicesErrorCheck(string[] description)method and just the temp variable to true all radio buttons save to the database table correctly BUT I then lose my erroring, which makes me thinks it is something to do with the way I have set up the message box, maybe.
Here is a screenshot of the prototype form just for reference. FitnessClassBooking Form
Here is a screenshot of the table while the app is running App Running Fitness Form
Here is the error being thrown with MemberID that has no 'Spin' class associated with it App Running Error
Here is my code in question -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace Membership_Formv2
{
public partial class FitnessClassBooking : Form
{
public FitnessClassBooking()
{
InitializeComponent();
}
private void bMainMenu_Click(object sender, EventArgs e)
{
new MainMenu().Show();
this.Hide();
}
private void fitnessInformationBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.fitnessInformationBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.databaseDataSet);
}
private void FitnessClassBooking_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'databaseDataSet.Members' table. You can move, or remove it, as needed.
this.membersTableAdapter.Fill(this.databaseDataSet.Members);
// TODO: This line of code loads data into the 'databaseDataSet.FitnessInformation' table. You can move, or remove it, as needed.
this.fitnessInformationTableAdapter.Fill(this.databaseDataSet.FitnessInformation);
}
private void fitnessInformationDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private string descriptionfit()
{
string className = "";
if (rbCardioClass.Checked == true)
{
className = "Cardio";
}
else if (rbSpinClass.Checked == true)
{
className = "Spin";
}
else if (rbPilatesClass.Checked == true)
{
className = "Pilates";
}
return className;
}
private string classDescription()
{
string serviceSeletionString = "Class";
if (rbCardioClass.Checked == true)
{
serviceSeletionString = rbCardioClass.Text;
this.Refresh();
}
else if (rbSpinClass.Checked == true)
{
serviceSeletionString = rbSpinClass.Text;
this.Refresh();
}
else if (rbPilatesClass.Checked == true)
{
serviceSeletionString = rbPilatesClass.Text;
this.Refresh();
}
return serviceSeletionString;
}
private bool errorCheckingID()
{
bool statusDB = true;
//Getting row info from MembersTa table
DatabaseDataSet.MembersRow newEntry = databaseDataSet.Members.FindByMemberID(Int32.Parse(textBox3.Text));
//Getting information from BookingTa table
if (newEntry == null)
{
statusDB = false;
return (statusDB);
}
return (statusDB);
}
public bool servicesErrorCheck(string[] description)
{
bool temp = true;
string serviceSeletionString = "";
if (rbCardioClass.Checked == true)
{
serviceSeletionString = rbCardioClass.Text;
this.Refresh();
}
else if (rbSpinClass.Checked == true)
{
serviceSeletionString = rbSpinClass.Text;
this.Refresh();
}
else if (rbPilatesClass.Checked == true)
{
serviceSeletionString = rbPilatesClass.Text;
this.Refresh();
}
for (int t = 0; t < description.Length; t++)
{
if (serviceSeletionString.Contains(description[t].Trim()))
{
temp = false;
break;
}
}
return (temp);
}
private string originalaccesdb()
{
string a = "";
DatabaseDataSet.FitnessInformationRow newRow = databaseDataSet.FitnessInformation.NewFitnessInformationRow();
newRow.Fitness_Booking_ID = databaseDataSet.FitnessInformation.Count + 1;
newRow.Description = descriptionfit();
newRow.MemberID = Int32.Parse(textBox3.Text);
databaseDataSet.FitnessInformation.AddFitnessInformationRow(newRow);
return a;
}
private string[] accessDB()
{
int t = 0;
int temp;
string[] servicesList = { "n", "n", "n" }; //This variable will store the data
//Same code too extract table information
foreach (DataRow r in databaseDataSet.FitnessInformation.Rows)
{
temp = Int32.Parse(r["MemberID"].ToString());
if (temp == Int32.Parse(textBox3.Text))
{
//Store inside the array all the services/description against the ID.
//Note that this array will remain "" for all the elements inside the array
//if no descritopn/services (i.e., record) is found against the input ID
servicesList[t] = r["Description"].ToString();
t = t + 1;
}
}
return (servicesList);
}
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
textBox1.Text = "";
int a = Int32.Parse(textBox2.Text);
DatabaseDataSet.MembersRow newID = databaseDataSet.Members.FindByMemberID(Int32.Parse(textBox2.Text));
string booking = "";
int temp;
foreach (DataRow r in databaseDataSet.FitnessInformation.Rows)
{
temp = Int32.Parse(r["MemberID"].ToString());
if (temp == Int32.Parse(textBox2.Text))
{
booking = r["Description"].ToString() + ", " + booking;
}
}
textBox1.Text = "Member ID is: " + (newID.MemberID).ToString() + Environment.NewLine +
"First Name is: " + (newID.First_Name).ToString() + Environment.NewLine +
"Last Name is: " + (newID.Last_Name).ToString() + Environment.NewLine +
"Bookings: " + booking;
}
public void button2_Click(object sender, EventArgs e)
{
bool status1, status2;
string[] description;
//Error control at the outer level for valid ID
status1 = errorCheckingID();
//Proceed only if ID is valid or status1 is true
if (status1)
{
//Retrieve information from the other database. Ideally you want this method to return
//an array containing registered services. This would be an array of strings.
description = accessDB();
//Services error checking
status2 = servicesErrorCheck(description);
//Now this is the code that would call the method to save data ito database
//when status2 and 2 are true
if (status2)
{
//Code for saving into database.
DatabaseDataSet.FitnessInformationRow newRow = databaseDataSet.FitnessInformation.NewFitnessInformationRow();
newRow.Fitness_Booking_ID = databaseDataSet.FitnessInformation.Count + 1;
newRow.Description = classDescription();
newRow.MemberID = Int32.Parse(textBox3.Text);
databaseDataSet.FitnessInformation.AddFitnessInformationRow(newRow);
}
else
{
//Show error that this service is not available
MessageBox.Show("This Class is already assigned to that Member ID");
}
}
else
{
//Error message invalid ID
MessageBox.Show("Invalid ID");
}
}
private void radioButton1_Click(object sender, EventArgs e)
{
}
private void radioButton4_Click(object sender, EventArgs e)
{
}
private void radioButton3_Click(object sender, EventArgs e)
{
}
}
}
I am really not sure why this is happening so I would really appreciate any help.
You are checking each string in descriptions as follows:
serviceSeletionString.Contains(description[t].Trim())
which considering at least one of the strings is just n it will always match Spin.
Quite why you are always returning an array with the blank ones having n, I don't know. Personally I would just use a List<string> and Add each item from the database to it. But that is a separate point.
Either change it to serviceSeletionString == description[t] (don't see why you need Trim()) or just replace the whole foreach loop with description.Contains(serviceSeletionString)
I have an active Google Places autocomplete working with Xamarin Forms or Cross Platform. I have a working solution that auto populates the address when the user types in the address. My problem is when the user selects it from the list the address does not go to the search_bar.text… The search bar just remains with the text that was typed? how can I get the text when selected to populate in the search bar.
I am new to Xamarin forms and C#.
public Createbusinessaccount ()
{
InitializeComponent ();
search_bar.ApiKey = GooglePlacesApiKey;
search_bar.Type = PlaceType.Address;
search_bar.Components = new Components("country:us"); // Restrict results to Australia and New Zealand
search_bar.PlacesRetrieved += Search_Bar_PlacesRetrieved;
search_bar.TextChanged += Search_Bar_TextChanged;
search_bar.MinimumSearchText = 2;
results_list.ItemSelected += Results_List_ItemSelected;
}
void Search_Bar_PlacesRetrieved(object sender, AutoCompleteResult result)
{
results_list.ItemsSource = result.AutoCompletePlaces;
spinner.IsRunning = false;
spinner.IsVisible = false;
if (result.AutoCompletePlaces != null && result.AutoCompletePlaces.Count > 0)
results_list.IsVisible = true;
}
void Search_Bar_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(e.NewTextValue))
{
results_list.IsVisible = false;
spinner.IsVisible = true;
spinner.IsRunning = true;
}
else
{
results_list.IsVisible = true;
spinner.IsRunning = false;
spinner.IsVisible = false;
}
}
async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var prediction = (AutoCompletePrediction)e.SelectedItem;
results_list.SelectedItem = null;
var place = await Places.GetPlace(prediction.Place_ID, GooglePlacesApiKey);
if (place != null)
await DisplayAlert(
place.Name, string.Format("Lat: {0}\nLon: {1}", place.Latitude, place.Longitude), "OK");
}
In your ItemSelected method, you need to set the text of the searchbar:
async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var prediction = (AutoCompletePrediction)e.SelectedItem;
search_bar.Text = prediction.Name? // Your property here
results_list.SelectedItem = null;
var place = await Places.GetPlace(prediction.Place_ID, GooglePlacesApiKey);
if (place != null)
await DisplayAlert(
place.Name, string.Format("Lat: {0}\nLon: {1}", place.Latitude, place.Longitude), "OK");
}
I am still trying to fix this, it only adds the street name and number not the whole address
Through the answers and help on a previous question. I have now come across another issue.
My btnDelete_MouseClick() event is not deleting the customer information that is stored in the textBox's.
I want it to take in the info like: Ashton Smith 864123456789
And then when the exact same info is in the corresponding textFields and I hit the delete button it removes it from the listBox.
This is what I have so far. It runs but it does not delete the customer from the listBox.
public partial class Form1 : Form
{
Customer cust;
public Form1()
{
InitializeComponent();
tbxFirstName.CharacterCasing = CharacterCasing.Upper;
tbxFirstName.MaxLength = 35;
tbxLastName.CharacterCasing = CharacterCasing.Upper;
tbxLastName.MaxLength = 35;
tbxPhone.MaxLength = 10;
listBoxDatabase.Name = "CUSTOMERS";
}
private void btnAddCustomer_MouseClick(object sender, MouseEventArgs e)
{
//string customer = tbxFirstName.Text + " " + tbxLastName.Text + " " + tbxPhone.Text;
cust = new Customer(tbxFirstName.Text, tbxLastName.Text, tbxPhone.Text);
if (listBoxDatabase.Items.Cast<Customer>().Any(x => x.ToString() == cust.ToString()))
{
MessageBox.Show("Customer Already Exist!", "ERROR");
}
else
{
listBoxDatabase.Items.Add(cust);
}
}
private void btnDelete_MouseClick(object sender, MouseEventArgs e)
{
Customer custToDelete = listBoxDatabase.Items.Cast<Customer>().FirstOrDefault(x => x.ToString() == cust.ToString());
if (custToDelete != null)
{
listBoxDatabase.Items.Remove(cust);
}
else
{
MessageBox.Show("No Customer Found!", "ERROR");
}
}
private void listBoxDatabase_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxDatabase.SelectedIndex != -1)
{
Customer cust = listBoxDatabase.Items[listBoxDatabase.SelectedIndex] as Customer;
tbxFirstName.Text = cust.getFirstName;
tbxLastName.Text = cust.getLastName;
tbxPhone.Text = cust.getPhone;
}
}
}
You logic for deletion is wrong. You should not use .ToString() to compare objects. You can Cast the Selected Item of the ListBox to your specific type and then Remove that from the items collection:
Customer selected = listBoxDatabase.SelectedItem as Customer;
if(selected != null)
listBoxDatabase.Items.Remove(selected);
else
MessageBox.Show("No Customer Found!", "ERROR");