i have an orderdetails page wherein customers can view their history page. And this is the url:
when i change the ID from 13 to lets say 14, it still shows the details on whats inside ID#14. What i want to happen is to have an error when customers try to change the localhost ID. Or to restrict the ID to be edited? Really dont have any idea on what to do. Encryption?
By the way here is the orderdetails code behind: (this is in user control)
public partial class ucCustomerOrder1 : System.Web.UI.UserControl
{
public bool CanIUpdateStatus;
public string TransactionNoText
{
get { return txtTransactionNo.Text; }
set { txtTransactionNo.Text = value; }
}
public bool IsAuthorizedToAddStatus
{
set { CanIUpdateStatus = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["IslandGasAdmin/ST"] == null)
{
txtTransactionNo.ReadOnly = true;
btnGo.Visible = false;
}
else
{
txtTransactionNo.ReadOnly = false;
btnGo.Visible = true;
}
if (txtTransactionNo.Text != string.Empty)
{
ShowOrderDetails(rblOrderDetails.SelectedValue, Convert.ToInt32(txtTransactionNo.Text));
}
else
{
rblOrderDetails.Visible = false;
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = false;
Panel4.Visible = false;
}
}
}
private void ShowOrderDetails(string PanelId, int OrderNo)
{
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = false;
Panel4.Visible = false;
rblOrderDetails.Visible = false;
if (IsOrderNoValid(OrderNo))
{
rblOrderDetails.Visible = true;
if (PanelId == "1")
{
ShoppingCart k = new ShoppingCart
{
Flag = OrderNo
};
DataTable dtCustomerDetails = k.GetOrderList();
if (dtCustomerDetails.Rows.Count > 0)
{
Panel1.Visible = true;
lblCustomerName.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerName"]);
lblCustomerPhoneNo.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerPhoneNo"]);
lblCustomerEmailID.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerEmailID"]);
lblTotalPrice.Text = String.Format("{0:#,000.00}",dtCustomerDetails.Rows[0]["TotalPrice"]);
lblTotalProducts.Text = Convert.ToString(dtCustomerDetails.Rows[0]["TotalProducts"]);
txtCustomerAddress.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerAddress"]);
lblPaymentMethod.Text = Convert.ToString(dtCustomerDetails.Rows[0]["PaymentMethod"]);
}
}
if (PanelId == "2")
{
Panel2.Visible = true;
ShoppingCart k = new ShoppingCart()
{
Flag = OrderNo
};
dlProducts.DataSource = k.GetTransactionDetails(); ;
dlProducts.DataBind();
}
if (PanelId == "3")
{
Panel3.Visible = true;
DropDownStatus.Visible = CanIUpdateStatus;
txtStatus.Visible = false;
//txtStatus.Visible = CanIUpdateStatus;
btnAdd.Visible = CanIUpdateStatus;
GetSetOrderStatus(0);
}
}
else
{
Panel4.Visible = true;
}
}
private bool IsOrderNoValid(int OrderNo)
{
ShoppingCart k = new ShoppingCart
{
Flag = OrderNo
};
DataTable dtCustomerDetails = k.GetOrderList();
if (dtCustomerDetails.Rows.Count > 0)
return true;
else
return false;
}
private void GetSetOrderStatus(int Flag)
{
ShoppingCart k = new ShoppingCart
{
OrderStatus = DropDownStatus.SelectedValue,
OrderNo = txtTransactionNo.Text,
Flag = Flag
};
DataTable dt = k.GetSetOrderStatus();
gvOrderStatus.DataSource = dt;
gvOrderStatus.DataBind();
//txtStatus.Text = string.Empty;
//DropDownStatus.SelectedValue = string.Empty;
}
please do help me, thank you
Related
I'm attempting to make a google map using Xamarin forms, the pins displays correctly and zooms in onto the user. It displays the inital map when the page starts, but when moving or zooming the map doesn't change and becomes grids if you zoom in enough. I can see my pin on the grid and everything, but I would like the map to load along with the pin.
public partial class IssueMap2 : ContentPage
{
public UIIssueVM Issue { get; set; }
public GeoLocation Location { get; set; }
public bool AllowPinMovment { get; set; }
private ExtendedMap.ExtendedMap map;
public Xamarin.Forms.Maps.Position OrgIssueLocation { get; set; }
bool IsGettingLocation = false;
bool bMapCtrlReady = false;
IGeolocator Locator;
public IssueMap2(UIIssueVM Issue, GeoLocation location)
{
AllowPinMovment = false;
this.Issue = Issue;
this.Location = location;
Title = "Map";
OrgIssueLocation = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
Locator = CrossGeolocator.Current;
if (Locator.DesiredAccuracy != 100)
Locator.DesiredAccuracy = 100;
if (Device.RuntimePlatform != Device.WinPhone)
{
InitializeComponent();
map = new ExtendedMap.ExtendedMap()
{
IsShowingUser = true,
HeightRequest = 100,
WidthRequest = 960,
VerticalOptions = LayoutOptions.FillAndExpand
};
map.LongTap += OnMapLongTap;
map.Ready += MapCtrlReady;
slMap.Children.Add(map);
}
}
public void MapCtrlReady(object sender, EventArgs args)
{
bMapCtrlReady = true;
}
public void OnMapLongTap(object sender, ExtendedMap.TapEventArgs args)
{
if (AllowPinMovment == false)
return;
if (Issue == null)
return;
var pos = args.Position;
// Update Issue
Issue.Latitude = pos.Latitude;
Issue.Longitude = pos.Longitude;
Issue.Changed = true;
// Update Pin
map.Pins.Clear();
AddPin(pos, Issue.Title, Issue.Description);
}
protected void AddPin(Xamarin.Forms.Maps.Position pos, String Title, String Desc)
{
// MAP pin does not like it if labels are empty
if (Title.Length == 0)
Title = "-";
if (Desc.Length == 0)
Desc = "-";
var pin = new Pin
{
Type = PinType.Place,
Position = pos,
Label = Title,
Address = Desc
};
map.Pins.Add(pin);
}
protected override void OnAppearing()
{
if (Device.RuntimePlatform == Device.WinPhone)
{
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
if (Issue.IsNew == false)
{
var position = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
AddPin(position, Issue.Title, Issue.Description);
MoveToPinLocation();
}
else // Issue is new
{
// Move to main location
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromMiles(1)));
// Get current location for new item
OnGetLocation();
}
}
}
protected override async void OnDisappearing()
{
if (Locator.IsListening)
{
await Locator.StopListeningAsync();
}
// Map controller crashes sometimes if we are to quick with exiting
await Task.Delay(500);
while (bMapCtrlReady == false)
{
await Task.Delay(500);
}
}
void OnButtonCenter(object sender, EventArgs args)
{
MoveToPinLocation();
}
void MoveToPinLocation()
{
double KmDistace = 0.5;
if (Issue != null)
{
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude), Distance.FromKilometers(KmDistace)));
}
else
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromKilometers(KmDistace)));
}
void OnButtonMainLocation(object sender, EventArgs args)
{
double KmDistace = 0.5;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromKilometers(KmDistace)));
}
void OnButtonGetLocation(object sender, EventArgs args)
{
OnGetLocation();
}
async void OnGetLocation()
{
if (IsGettingLocation == true)
return; // already getting location
try
{
if (Locator.IsListening == true)
{
await Locator.StopListeningAsync();
}
if (Locator.IsGeolocationAvailable == false)
{
lbPosText.Text = "GeoLocation is not available.";
this.ForceLayout();
return;
}
if (Locator.IsGeolocationEnabled == false)
{
lbPosText.Text = "GeoLocation is not enabled.";
this.ForceLayout();
return;
}
IsGettingLocation = true;
IsBusy = true;
slCommands.IsVisible = false;
aActIndicator.IsVisible = true;
aActIndicator.IsRunning = true;
lbPosText.Text = "Searching for GPS location...";
this.ForceLayout();
TimeSpan timeSpan = TimeSpan.FromTicks(120 * 1000);
var position = await Locator.GetPositionAsync(timeSpan);
// Update Issue Position
Issue.Latitude = position.Latitude;
Issue.Longitude = position.Longitude;
Issue.Changed = true;
// Update Pin Postion
var pos = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
map.Pins.Clear();
AddPin(pos, Issue.Title, Issue.Description);
UpdateGPSLocationText();
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
IsGettingLocation = false;
IsBusy = false;
slCommands.IsVisible = true;
this.ForceLayout();
// Center map around pin
MoveToPinLocation();
}
catch (Exception /*ex*/)
{
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
IsGettingLocation = false;
IsBusy = false;
slCommands.IsVisible = true;
lbPosText.Text = "Unable to find position!";
lbPosText.IsVisible = true;
this.ForceLayout();
}
}
void UpdateGPSLocationText()
{
String text = String.Format("{0} x {1}", Issue.Longitude, Issue.Latitude);
lbPosText.Text = text;
}
}
}
Android extended map renderer
[assembly: ExportRenderer(typeof(ExtendedMap.ExtendedMap), typeof(ExtendedMapRenderer))]
namespace ExtendedMap.Android
{
public class ExtendedMapRenderer : MapRenderer, IOnMapReadyCallback
{
private GoogleMap _map;
public ExtendedMapRenderer()
{
}
public ExtendedMapRenderer(IntPtr javaReference, JniHandleOwnership jniHandleOwnership)
{
int x = 0;
x++;
}
private void InvokeOnMapReadyBaseClassHack(GoogleMap googleMap)
{
System.Reflection.MethodInfo onMapReadyMethodInfo = null;
Type baseType = typeof(MapRenderer);
foreach (var currentMethod in baseType.GetMethods(System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.DeclaredOnly))
{
if (currentMethod.IsFinal && currentMethod.IsPrivate)
{
if (string.Equals(currentMethod.Name, "OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
if (currentMethod.Name.EndsWith(".OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
}
}
if (onMapReadyMethodInfo != null)
{
onMapReadyMethodInfo.Invoke(this, new[] { googleMap });
}
}
void IOnMapReadyCallback.OnMapReady(GoogleMap googleMap)
{
InvokeOnMapReadyBaseClassHack(googleMap);
_map = googleMap;
if (_map != null)
{
_map = googleMap;
this.NativeMap = googleMap;
_map.MapClick += googleMap_MapClick;
_map.MapLongClick += googleMap_MapLongClick;
((ExtendedMap)Element).OnReady();
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
if (_map != null)
_map.MapClick -= googleMap_MapClick;
base.OnElementChanged(e);
if (Control != null)
((MapView)Control).GetMapAsync(this);
}
private void googleMap_MapClick(object sender, GoogleMap.MapClickEventArgs e)
{
((ExtendedMap)Element).OnTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
private void googleMap_MapLongClick(object sender, GoogleMap.MapLongClickEventArgs e)
{
((ExtendedMap)Element).OnLongTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
}
}
I would double check the Google Maps API key on the manifest of your application!
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzr3yCpVgSOXvTgri29nC6KqFbdO73QmoVQWEw" />
As well as your SHA-1 key of your keystore on the Google API Credential Dashboard.
i have a list of objects saved in a text file that I can display onto a form. However now I need a button that will only display certain objects from the list based on a property, in my case brand. Below is the code I've been trying to use but cant get it to work.
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Car> BrandSelect = new List<Car>(cars);
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
DisplayCar();
}
Underneath is the full code, in case more information is needed, thanks for your help.
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.IO;
namespace Car_Manager
{
public partial class Form1 : Form
{
string currentfile;
Car c;
int curIndex = -1;
List<Car> cars = new List<Car>();
public Form1()
{
InitializeComponent();
c = new Car();
saveFileDialog1.CreatePrompt = true;
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.FileName = "myText";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter =
"Text files (*.txt)|*.txt|All files (*.*)|*.*";
}
public void clearForm()
{
txtBrand.Text = "";
txtModel.Text = "";
txtYear.Text = "";
txtPrice.Text = "";
txtNumMiles.Text = "";
txtInformation.Text = "";
radAutomatic.Checked = false;
radManual.Checked = false;
radConvertible.Checked = false;
radCoupe.Checked = false;
radEstate.Checked = false;
radHatchback.Checked = false;
radHPV.Checked = false;
radSaloon.Checked = false;
radSUV.Checked = false;
}
private void DisplayCar()
{
txtBrand.Text = c.Brand;
txtModel.Text = c.Model;
txtYear.Text = c.Year;
txtPrice.Text = c.Price;
txtNumMiles.Text = c.NumMiles;
DisplayBody();
DisplayGear();
string str = "";
for (int i = 0; i < c.Information.Count(); i++)
str += c.Information[i] + "\r\n";
txtInformation.Text = str;
}
private void FormToObject()
{
c.Brand = txtBrand.Text;
c.Model = txtModel.Text;
c.Year = txtYear.Text;
c.Price = txtPrice.Text;
c.NumMiles = txtNumMiles.Text;
BodyCheck();
GearCheck();
}
private void BodyCheck()
{
if (radHatchback.Checked == true)
{ c.Body = radHatchback.Text; }
else if (radHPV.Checked == true)
{ c.Body = radHPV.Text; }
else if (radSUV.Checked == true)
{ c.Body = radSUV.Text; }
else if (radSaloon.Checked == true)
{ c.Body = radSaloon.Text; }
else if (radConvertible.Checked == true)
{ c.Body = radConvertible.Text; }
else if (radCoupe.Checked == true)
{ c.Body = radCoupe.Text; }
else if (radEstate.Checked == true)
{ c.Body = radEstate.Text; }
}
private void DisplayBody()
{
if (c.Body == "Hatchback")
{ radHatchback.PerformClick(); }
else if (c.Body == "HPV")
{ radHPV.PerformClick(); }
else if (c.Body == "SUV")
{ radSUV.PerformClick(); }
else if (c.Body == "Convertible")
{ radConvertible.PerformClick(); }
else if (c.Body == "Saloon")
{ radSaloon.PerformClick(); }
else if (c.Body == "Coupe")
{ radSaloon.PerformClick(); }
else if (c.Body == "Estate")
{ radEstate.PerformClick(); }
}
private void GearCheck()
{
if (radAutomatic.Checked == true)
{ c.GearBox = radAutomatic.Text; }
else if (radManual.Checked == true)
{ c.GearBox = radManual.Text; }
}
private void DisplayGear()
{
if (c.GearBox == "Manual")
{ radManual.PerformClick(); }
else if (c.GearBox == "Automatic")
{ radAutomatic.PerformClick(); }
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
currentfile = openFileDialog1.FileName;
saveToolStripMenuItem.Enabled = true;
Stream s1 = openFileDialog1.OpenFile();
StreamReader reader = new StreamReader(s1);
while (reader.Peek() != -1)
{
string str = reader.ReadLine();
Car c = new Car();
c.ReadString(str);
cars.Add(c);
}
curIndex = 0;
c = cars[curIndex];
DisplayCar();
reader.Close();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save everything in a dialog box
saveFileDialog1.ShowDialog();
// Open the file and save the information
Stream textOut = saveFileDialog1.OpenFile();
StreamWriter writer = new StreamWriter(textOut);
FormToObject();
string str = c.GetToString();
writer.WriteLine(str);
writer.Close();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save the file with the current file name
FileStream f1 = new FileStream(currentfile, FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(f1);
// get the object into a string
FormToObject();
StreamWriter file = new System.IO.StreamWriter(f1);
cars.ForEach(file.WriteLine);
file.Close();
}
private void btnAddInfo_Click(object sender, EventArgs e)
{
c.Information.Add(txtAddInfo.Text);
string str = "";
for (int i = 0; i < c.Information.Count(); i++)
str += c.Information[i] + "\r\n";
txtInformation.Text = str;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtInformation.Text = "";
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void btnPreviousCar_Click(object sender, EventArgs e)
{
curIndex--;
if (curIndex < 0)
curIndex = cars.Count - 1;
c = cars[curIndex];
DisplayCar();
}
private void btnNextCar_Click(object sender, EventArgs e)
{
curIndex++;
if (curIndex >= cars.Count)
curIndex = 0;
c = cars[curIndex];
DisplayCar();
}
private void button1_Click(object sender, EventArgs e)
{
int a = cars.Count;
textBox1.Text = Convert.ToString(cars[2]);
}
private void btnEditCar_Click(object sender, EventArgs e)
{
txtBrand.ReadOnly = false;
txtModel.ReadOnly = false;
txtYear.ReadOnly = false;
txtPrice.ReadOnly = false;
txtNumMiles.ReadOnly = false;
txtAddInfo.ReadOnly = false;
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Car> BrandSelect = new List<Car>(cars);
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
DisplayCar();
}
private void yearToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
}
class Car
{
//List of properties
private string brand;
private string model;
private string year;
private string price;
private string numMiles;
private string body;
private string gearbox;
private List<string> information;
//Constructor
public Car() //Default Constructor
{
brand = "Unknown";
model = "Unknown";
year = "Unknown";
price = "Unknown";
numMiles = "Unknown";
information = new List<string>();
}
public Car(string str)
{
information = new List<string>();
ReadString(str);
}
public void ReadString(string str)
{
string[] words = str.Split('|');
int Nwords = words.Count();
brand = words[0];
model = words[1];
year = words[2];
price = words[3];
numMiles = words[4];
body = words[5];
gearbox = words[6];
information.Clear();
for (int i = 7; i < Nwords; i++)
information.Add(words[i]);
}
//Methods
public string Brand
{
get { return brand; }
set { brand = value; }
}
public string Model
{
get { return model; }
set { model = value; }
}
public string Year
{
get { return year; }
set { year = value; }
}
public string Price
{
get { return price; }
set { price = value; }
}
public string NumMiles
{
get { return numMiles; }
set { numMiles = value; }
}
public string Body
{
get { return body; }
set { body = value; }
}
public string GearBox
{
get { return gearbox; }
set { gearbox = value; }
}
public List<string> Information
{
get { return information; }
set { information = value; }
}
public string GetToString()
{
string str = "";
str += brand + "|";
str += model + "|";
str += year + "|";
str += price + "|";
str += numMiles + "|";
str += body + "|";
str += gearbox + "|";
for (int i = 0; i < information.Count(); i++)
str += information[i] + "|";
return str;
}
}
}
First thing that I noticed:
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
// You already have list of cars, this line will copy your list
// into a new one, which is unnecessary work (you don't use it later).
// You don't need this:
List<Car> BrandSelect = new List<Car>(cars);
// the "c" here is not the "c" that is the field of your form
// it's a part of the syntax of linq query
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
// This method displays what is in the field "c" (this.c)
// ... and the content of "c" didn't change at all
DisplayCar();
}
the code here should be, for example:
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
//beware this can be null
this.c = (from a in this.cars
where a.Brand == textBox1.Text
select a).FirstOrDefault();
}
[msdn] introduction to linq queries
these is my code for setting session object. i want to use that object to get the infomation of login user. but i am unable to do that i get the error 'Input String is not in correct format'. i need help here to know how to create an object & get values from my session object
public UserLoginDetails LoggedUserDetails
{
set { Session["loggeduserdetails"] = value; }
get
{
if (Session["loggeduserdetails"] == null)
{
if (Session["username"] == null)
{
Response.Redirect("../Authentication/Login.aspx");
}
if (Session["password"] == null)
{
Response.Redirect("../Authentication/Login.aspx");
}
DAL.LoginHistoryDAL LoginDAL = new DAL.LoginHistoryDAL();
DataSet Ds = LoginDAL.AuthenticateUser(Session["username"].ToString(), EncryptionUtility.Encrypt(Session["password"].ToString()));
UserLoginDetails ULD = new UserLoginDetails();
if (Ds.Tables[0].Rows.Count > 0)
{
// Populating UserObj
bool IsAdmin = false;
bool IsMasterAdmin = false;
if (Ds.Tables[0].Rows[0]["IsAdmin"].ToString() == "1")
{
IsAdmin = true;
}
else
{
IsAdmin = false;
}
if (Ds.Tables[0].Rows[0]["IsMasterAdmin"].ToString() == "1")
{
IsMasterAdmin = true;
}
else
{
IsMasterAdmin = false;
}
ULD = new UserLoginDetails();
ULD.UserId = int.Parse(Ds.Tables[0].Rows[0]["UserId"].ToString());
ULD.IsAdmin = IsAdmin;
ULD.IsMasterAdmin = IsMasterAdmin;
ULD.UserName = Ds.Tables[0].Rows[0]["FullName"].ToString();
ULD.LocationID = int.Parse(Ds.Tables[0].Rows[0]["LocationID"].ToString());
ULD.FullName = Ds.Tables[0].Rows[0]["FullName"].ToString();
ULD.StatusId = int.Parse(Ds.Tables[0].Rows[0]["StatusId"].ToString());
ULD.Email = Ds.Tables[0].Rows[0]["Email"].ToString();
ULD.CellNo = Ds.Tables[0].Rows[0]["Cell"].ToString();
ULD.CityId = int.Parse(Ds.Tables[0].Rows[0]["CityID"].ToString());
ULD.StateId = int.Parse(Ds.Tables[0].Rows[0]["StateId"].ToString());
ULD.CountryId = int.Parse(Ds.Tables[0].Rows[0]["CountryID"].ToString());
}
Session["loggeduserdetails"] = ULD;
}
return (UserLoginDetails)Session["loggeduserdetails"];
}
}
}
public class UserLoginDetails
{
public int UserId = 0;
public bool IsAdmin = false;
public bool IsMasterAdmin = false;
public string UserName = string.Empty;
public int LocationID = 0;
public string FullName = string.Empty;
public int StatusId = 0;
public string Email = string.Empty;
public string CellNo = string.Empty;
public int CityId = 0;
public int StateId = 0;
public int CountryId = 0;
}
Looks like one of the pieces of data you expect to be a numeric value isn't.
I.e. UserId, or CityID isn't a numeric value or any other.
I would have a look at one of the following lines of code:
ULD.UserId = int.Parse(Ds.Tables[0].Rows[0]["UserId"].ToString());
ULD.LocationID = int.Parse(Ds.Tables[0].Rows[0]["LocationID"].ToString());
ULD.StatusId = int.Parse(Ds.Tables[0].Rows[0]["StatusId"].ToString());
ULD.CityId = int.Parse(Ds.Tables[0].Rows[0]["CityID"].ToString());
ULD.StateId = int.Parse(Ds.Tables[0].Rows[0]["StateId"].ToString());
ULD.CountryId = int.Parse(Ds.Tables[0].Rows[0]["CountryID"].ToString());
I create a custom grid control by extending the DataGridView in windows forms application. I use some custom functions for setting column readonly and some other functionalities. My current problem is when I use multiple controls in same form, it only reflects function execution output for the last control only. How make each control a separate instance of the user control?
public partial class dGridView : DataGridView
{
#region Member variables
DatagridViewCheckBoxHeaderCell chkHeader;
bool NeedToPopulateColumns = true;
public event DatagridViewCellButtonClickedHandler CellButtonClicked;
private int currentComboSelIndex;
#endregion
public dGridView()
{
InitializeComponent();
if (!DesignMode)
{
this.DoubleBuffered = true;
this.AutoGenerateColumns = false;
this.CellButtonClicked += new DatagridViewCellButtonClickedHandler(dGridView_CellButtonClicked);
}
}
#region Properties
/// <summary>
/// Gets or sets the datasource used to define columns.
/// </summary>
public object DesignDataSource
{
get;
set;
}
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool ExtendLastColumn
{
get;
set;
}
private List<string> AutoFilterColumnNames
{
get;
set;
}
private List<string> HiddenColumnsList
{
get;
set;
}
private List<string> ReadOnlyColumnsList
{
get;
set;
}
private List<string> ButtonColumnsList
{
get;
set;
}
private List<DGVSupportClass.ComboBoxColumns> ComboBoxColumnsList
{
get;
set;
}
private List<CustomCaptions> customCaptionList
{
get;
set;
}
#endregion
#region Methods
#region Public Methods
public void AddFilterToColumns(List<string> columnNames)
{
if (columnNames.Count > 0)
{
this.AutoFilterColumnNames = columnNames;
}
}
public void HiddenColumns(List<string> columnNames)
{
if (columnNames.Count > 0)
{
this.HiddenColumnsList = columnNames;
HideColumnsInList(this.HiddenColumnsList);
}
}
public void ReadOnlyColumns(List<string> columnNames)
{
if (columnNames.Count > 0)
{
this.ReadOnlyColumnsList = columnNames;
ReadOnlyColumnsInList(this.ReadOnlyColumnsList);
}
}
public void ReadOnlyRow(int rowIndex)
{
if (this.DataSource == null)
{
return;
}
this.Rows[rowIndex].ReadOnly = true;
}
public void AddButtonToCells(List<string> columnNames)
{
this.ButtonColumnsList = columnNames;
NeedToPopulateColumns = true;
FindBindingDataObjectType();
}
public void AddComboBoxColumn(List<DGVSupportClass.ComboBoxColumns> comboBoxColumns)
{
this.ComboBoxColumnsList = comboBoxColumns;
NeedToPopulateColumns = true;
FindBindingDataObjectType();
}
public void SetCustomDataSourceToComboBoxCell(int colIndex, int rowIndex, object cboxDataSource, string displayMember, string valueMember)
{
if (this.Columns[colIndex].GetType() != typeof(DataGridViewComboBoxColumn))
{
throw new Exception(string.Format("Column [{0}] is not a DataGridViewComboBoxColumn", colIndex));
}
if (string.IsNullOrEmpty(displayMember) || string.IsNullOrEmpty(valueMember))
{
throw new Exception("Display and Value Member must be passed");
}
DataGridViewComboBoxCell combo = this[colIndex, rowIndex] as DataGridViewComboBoxCell;
combo.DataSource = cboxDataSource;
combo.DisplayMember = displayMember;
combo.ValueMember = valueMember;
}
public void SetCustomDataSourceToComboBoxCell(int colIndex, int rowIndex, string[] cboxDataSource)
{
if (this.Columns[colIndex].GetType() != typeof(DataGridViewComboBoxColumn))
{
throw new Exception(string.Format("Column [{0}] is not a DataGridViewComboBoxColumn", colIndex));
}
DataGridViewComboBoxCell combo = this[colIndex, rowIndex] as DataGridViewComboBoxCell;
combo.DataSource = cboxDataSource;
}
public void CustomColumnCaptions(List<CustomCaptions> newColumnCaptions)
{
if (newColumnCaptions == null || newColumnCaptions.GetType() == typeof(System.DBNull))
{
return;
}
if (this.customCaptionList != newColumnCaptions)
this.customCaptionList = newColumnCaptions;
foreach (CustomCaptions col in newColumnCaptions)
{
if (this.Columns[col.ColumnName] != null)
this.Columns[col.ColumnName].HeaderCell.Value = col.ColumnCaption;
}
}
public void SetCustomColumnCaption(string columnName, string newCaption)
{
if (this.Columns.Contains(columnName))
{
if (this.Columns[columnName] != null)
this.Columns[columnName].HeaderCell.Value = newCaption;
}
CustomCaptions cap = new CustomCaptions(columnName, newCaption);
if (!customCaptionList.Contains(cap))
{
customCaptionList.Add(cap);
}
}
#endregion
#region Private Methods
private void AddFilterToColumnsInList(List<string> columnNames)
{
if (this.DataSource == null || columnNames == null)
{
return;
}
foreach (DataGridViewColumn col in this.Columns)
{
if (col.GetType() == typeof(DataGridViewTextBoxColumn) && columnNames.Contains(col.Name))
col.HeaderCell = new
DataGridViewAutoFilter.DataGridViewAutoFilterColumnHeaderCell(col.HeaderCell);
}
}
private void HideColumnsInList(List<string> columnNames)
{
if (this.DataSource == null || columnNames == null)
{
return;
}
foreach (DataGridViewColumn col in this.Columns)
{
if (this.HiddenColumnsList.Contains(col.Name))
{
col.Visible = false;
}
}
}
/// <summary>
/// Finds the type of the binding data object.
/// </summary>
private void FindBindingDataObjectType()
{
this.SuspendLayout();
this.ScrollBars = ScrollBars.None;
if (NeedToPopulateColumns)
{
if (this.DataSource is System.Collections.IList && this.DataSource.GetType().IsGenericType)
{
PopulateDataGridColumnsFromICartItem();
}
else
{
PopulateDataGridColumnsFromDataView();
}
NeedToPopulateColumns = false;
if (this.customCaptionList != null && this.customCaptionList.GetType() != typeof(System.DBNull))
{
CustomColumnCaptions(this.customCaptionList);
}
}
this.ScrollBars = ScrollBars.Both;
this.ResumeLayout();
}
/// <summary>
/// Populates the DataGridView columns with controls according to the
/// DataType of each columns which it represents. e.g. when a boolean
/// value found, then a DataGridViewCheckBoxColumn will be added and
/// for datetime it will be ESCalendarColumn (a custom control).
/// </summary>
private void PopulateDataGridColumnsFromDataView()
{
bool isComboAdded = false;
DataTable dt = null;
if (null == this.DataSource)
{
return;
}
else
{
switch (this.DataSource.GetType().ToString())
{
case "System.Data.DataTable":
dt = (DataTable)this.DataSource;
break;
case "System.Data.DataView":
dt = ((DataView)this.DataSource).Table;
break;
case "System.Data.DataSet":
dt = ((DataSet)this.DataSource).Tables[0];
break;
case "System.Windows.Forms.BindingSource":
if (((BindingSource)this.DataSource).DataSource.GetType() == typeof(DataTable))
{
dt = (DataTable)((BindingSource)this.DataSource).DataSource;
}
break;
default:
return;
}
}
this.Columns.Clear();
foreach (DataColumn dc in dt.Columns)
{
if (ButtonColumnsList != null && ButtonColumnsList.Contains(dc.ColumnName))
{
DataGridViewButtonColumn dvButton = new DataGridViewButtonColumn();
dvButton.Name = dc.ColumnName;
dvButton.HeaderText = dc.ColumnName;
this.Columns.Add(dvButton);
this.Columns[dvButton.Name].DataPropertyName = dvButton.Name;
continue;
}
if (ComboBoxColumnsList != null && ComboBoxColumnsList.Count > 0)
{
foreach (DGVSupportClass.ComboBoxColumns tmpData in ComboBoxColumnsList)
{
if (tmpData.ColumnName == dc.ColumnName)
{
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.DataPropertyName = dc.ColumnName;
comboCol.Name = dc.ColumnName;
comboCol.HeaderText = dc.ColumnName;
comboCol.DataSource = tmpData.DataSource;
if (!string.IsNullOrEmpty(tmpData.Display))
{
comboCol.DisplayMember = tmpData.Display;
comboCol.ValueMember = tmpData.Value;
}
comboCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
comboCol.FlatStyle = FlatStyle.Standard;
this.Columns.Add(comboCol);
isComboAdded = true;
break;
}
}
}
if (isComboAdded)
{
isComboAdded = false;
continue;
}
switch (((DataColumn)dc).DataType.ToString())
{
case "System.String":
case "System.Int32":
case "System.Int64":
case "System.Decimal":
case "System.Guid":
this.Columns.Add(dc.ColumnName, dc.Caption);
this.Columns[dc.ColumnName].DataPropertyName = dc.ColumnName;
this.Columns[dc.ColumnName].SortMode = DataGridViewColumnSortMode.Automatic;
break;
case "System.Boolean":
DataGridViewCheckBoxColumn chkbox = new DataGridViewCheckBoxColumn();
chkHeader = new DatagridViewCheckBoxHeaderCell();
chkbox.HeaderCell = chkHeader;
chkbox.Name = "chkBox" + dc.ColumnName;
chkbox.HeaderText = dc.ColumnName;
chkHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(chkHeader_OnCheckBoxClicked);
this.Columns.Add(chkbox);
this.Columns[chkbox.Name].DataPropertyName = dc.ColumnName;
this.Columns[chkbox.Name].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
this.Columns[chkbox.Name].SortMode = DataGridViewColumnSortMode.NotSortable;
break;
case "System.DateTime":
ESCalendarColumn calendarCol = new ESCalendarColumn();
calendarCol.Name = ((DataColumn)dc).ColumnName;
calendarCol.HeaderText = ((DataColumn)dc).Caption;
this.Columns.Add(calendarCol);
this.Columns[calendarCol.Name].DataPropertyName = calendarCol.Name;
this.Columns[calendarCol.Name].SortMode = DataGridViewColumnSortMode.Automatic;
break;
default:
if (((DataColumn)dc).DataType.IsEnum)
{
List<DGVSupportClass.EnumToComboClass> lstCbo = new List<DGVSupportClass.EnumToComboClass>();
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.DataPropertyName = ((DataColumn)dc).ColumnName;
comboCol.Name = ((DataColumn)dc).ColumnName;
comboCol.HeaderText = ((DataColumn)dc).Caption;
comboCol.DataSource = Enum.GetValues(dc.DataType);
comboCol.FlatStyle = FlatStyle.Standard;
if (((DataColumn)dc).ReadOnly) comboCol.ReadOnly = true;
this.Columns.Add(comboCol);
}
else
{
this.Columns.Add(dc.ColumnName, dc.Caption);
this.Columns[dc.ColumnName].DataPropertyName = dc.ColumnName;
this.Columns[dc.ColumnName].SortMode = DataGridViewColumnSortMode.Automatic;
}
break;
}
}
NeedToPopulateColumns = false;
AddFilterToColumnsInList(this.AutoFilterColumnNames);
HideColumnsInList(this.HiddenColumnsList);
// Extend the last column
if (this.ExtendLastColumn)
{
this.Columns[this.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
/// <summary>
/// Populates the DataGridView columns with controls according to the
/// DataType of each columns which it represents. e.g. when a boolean
/// value found, then a DataGridViewCheckBoxColumn will be added and
/// for datetime it will be ESCalendarColumn (a custom control).
/// </summary>
private void PopulateDataGridColumnsFromICartItem()
{
this.Columns.Clear();
System.Reflection.PropertyInfo[] propertyInfos = null;
bool isComboAdded = false;
if (this.DesignDataSource != null)
{
if (this.DesignDataSource != null && this.DesignDataSource is System.Collections.IList && this.DesignDataSource.GetType().IsGenericType)
{
if (((System.Collections.IList)this.DesignDataSource).Count > 0 && (((System.Collections.IList)this.DesignDataSource)[0]) != null)
{
propertyInfos = (((System.Collections.IList)this.DesignDataSource)[0]).GetType().GetProperties();
}
else
{
propertyInfos = this.DesignDataSource.GetType().GetProperties();
propertyInfos = propertyInfos[propertyInfos.Length - 1].PropertyType.GetProperties();
}
}
}
else
{
if (this.DataSource != null && this.DataSource is System.Collections.IList && this.DataSource.GetType().IsGenericType)
{
if (((System.Collections.IList)this.DataSource).Count > 0)
{
propertyInfos = (((System.Collections.IList)this.DataSource)[0]).GetType().GetProperties();
}
else
{
propertyInfos = this.DataSource.GetType().GetProperties();
propertyInfos = propertyInfos[propertyInfos.Length - 1].PropertyType.GetProperties();
}
}
}
if (propertyInfos != null)
{
foreach (var item in propertyInfos)
{
if (ComboBoxColumnsList != null && ComboBoxColumnsList.Count > 0)
{
foreach (DGVSupportClass.ComboBoxColumns tmpData in ComboBoxColumnsList)
{
if (tmpData.ColumnName == item.Name)
{
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.DataPropertyName = item.Name;
comboCol.Name = item.Name;
comboCol.HeaderText = item.Name;
comboCol.DataSource = tmpData.DataSource;
if (!string.IsNullOrEmpty(tmpData.Display))
{
comboCol.DisplayMember = tmpData.Display;
comboCol.ValueMember = tmpData.Value;
}
comboCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
comboCol.FlatStyle = FlatStyle.Standard;
this.Columns.Add(comboCol);
isComboAdded = true;
break;
}
}
}
if (isComboAdded)
{
isComboAdded = false;
continue;
}
if (ButtonColumnsList != null && ButtonColumnsList.Contains(item.Name))
{
DataGridViewButtonColumn dvButton = new DataGridViewButtonColumn();
dvButton.Name = item.Name;
dvButton.HeaderText = item.Name;
this.Columns.Add(dvButton);
this.Columns[dvButton.Name].DataPropertyName = dvButton.Name;
}
else
{
switch (item.PropertyType.ToString())
{
case "System.String":
case "System.Int32":
case "System.Int64":
case "System.Decimal":
case "System.Guid":
DataGridViewTextBoxColumn txtBox = new DataGridViewTextBoxColumn();
txtBox.Name = item.Name;
this.Columns.Add(txtBox);
this.Columns[item.Name].DataPropertyName = item.Name;
break;
case "System.Boolean":
DataGridViewCheckBoxColumn chkbox = new DataGridViewCheckBoxColumn();
chkHeader = new DatagridViewCheckBoxHeaderCell();
chkbox.HeaderCell = chkHeader;
chkbox.Name = "chkBox" + item.Name;
chkbox.HeaderText = item.Name;
chkHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(chkHeader_OnCheckBoxClicked);
this.Columns.Add(chkbox);
this.Columns[chkbox.Name].DataPropertyName = item.Name;
this.Columns[chkbox.Name].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
this.Columns[chkbox.Name].SortMode = DataGridViewColumnSortMode.NotSortable;
break;
case "System.DateTime":
ESCalendarColumn calendarCol = new ESCalendarColumn();
calendarCol.Name = item.Name;
calendarCol.HeaderText = item.Name;
this.Columns.Add(calendarCol);
this.Columns[calendarCol.Name].DataPropertyName = calendarCol.Name;
break;
default:
if (item.PropertyType.IsEnum && item.PropertyType.IsPublic)
{
List<DGVSupportClass.EnumToComboClass> lstCbo = new List<DGVSupportClass.EnumToComboClass>();
foreach (System.Reflection.FieldInfo fInfo in item.PropertyType.GetFields(
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
lstCbo.Add(new DGVSupportClass.EnumToComboClass(fInfo.Name, fInfo.GetRawConstantValue().ToString()));
}
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.DataPropertyName = item.Name;
comboCol.Name = item.Name;
comboCol.HeaderText = item.Name;
comboCol.DataSource = lstCbo;
comboCol.DisplayMember = "Display";
comboCol.ValueMember = "Value";
comboCol.FlatStyle = FlatStyle.Standard;
this.Columns.Add(comboCol);
}
else if (!item.PropertyType.IsAbstract)
{
DataGridViewTextBoxColumn txtBoxDefault = new DataGridViewTextBoxColumn();
txtBoxDefault.Name = item.Name;
txtBoxDefault.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.Columns.Add(txtBoxDefault);
this.Columns[item.Name].DataPropertyName = item.Name;
}
break;
}
}
}
}
if (this.ExtendLastColumn)
{
this.Columns[this.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
AddFilterToColumnsInList(this.AutoFilterColumnNames);
HideColumnsInList(this.HiddenColumnsList);
}
#endregion
#endregion
#region Events
protected override void OnDataSourceChanged(EventArgs e)
{
if (this.DesignDataSource == null)
{
this.DesignDataSource = this.DataSource;
NeedToPopulateColumns = true;
}
FindBindingDataObjectType();
base.OnDataSourceChanged(e);
}
protected override void OnCellContentClick(DataGridViewCellEventArgs e)
{
if (this.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewButtonColumn))
{
DatagridViewCellButtonClickEventArgs dc = new DatagridViewCellButtonClickEventArgs(this.CurrentCell.Value.ToString(),
this.CurrentCell.Tag, this.CurrentCell.ColumnIndex, this.CurrentCell.RowIndex, this.CurrentCell.Value);
if (CellButtonClicked != null) { CellButtonClicked(this, dc); }
}
else if (this.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewComboBoxColumn))
{
this.CurrentCell = this[e.ColumnIndex, e.RowIndex];
this.BeginEdit(false);
ComboBox comboBox = this.EditingControl as ComboBox;
if (comboBox != null)
{
comboBox.DroppedDown = true;
}
}
base.OnCellContentClick(e);
}
protected override void OnCellClick(DataGridViewCellEventArgs e)
{
if (this.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewComboBoxColumn))
{
this.CurrentCell = this[e.ColumnIndex, e.RowIndex];
this.BeginEdit(false);
ComboBox comboBox = this.EditingControl as ComboBox;
if (comboBox != null)
{
comboBox.DroppedDown = true;
}
}
base.OnCellClick(e);
}
protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
{
base.OnDataBindingComplete(e);
}
protected override void OnColumnHeaderMouseClick(DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
List<ColumnSettingsClass> LCss = new List<ColumnSettingsClass>();
foreach (DataGridViewColumn col in this.Columns)
{
if (!HiddenColumnsList.Contains(col.Name))
{
LCss.Add(new ColumnSettingsClass(col.Name, col.HeaderText, col.Width, col.Index, col.Visible));
}
}
ColumnSettings frmCs = new ColumnSettings(ref LCss);
frmCs.ShowDialog(this);
foreach (ColumnSettingsClass item in LCss)
{
if (this.Columns.Contains(item.ColumnName))
{
this.Columns[item.ColumnName].DisplayIndex = item.ColumnOrdinal;
this.Columns[item.ColumnName].Width = item.ColumnWidth;
this.Columns[item.ColumnName].Visible = item.Visibility;
}
}
}
base.OnColumnHeaderMouseClick(e);
}
protected override void OnCurrentCellDirtyStateChanged(EventArgs e)
{
base.OnCurrentCellDirtyStateChanged(e);
this.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is ComboBox)
{
ComboBox comboBox = e.Control as ComboBox;
comboBox.SelectedIndexChanged -= new EventHandler(LastColumnComboSelectionChanged);
comboBox.SelectedIndexChanged += new EventHandler(LastColumnComboSelectionChanged);
if (comboBox != null)
comboBox.DropDown += delegate(object s, EventArgs se) { ((ComboBox)s).BackColor = this.DefaultCellStyle.BackColor; };
}
base.OnEditingControlShowing(e);
}
private void LastColumnComboSelectionChanged(object sender, EventArgs e)
{
var currentcell = this.CurrentCellAddress;
var sendingCB = sender as DataGridViewComboBoxEditingControl;
if (sendingCB.EditingControlValueChanged)
{
DataGridViewTextBoxCell cel = (DataGridViewTextBoxCell)this.Rows[currentcell.Y].Cells[0];
cel.Value = sendingCB.EditingControlFormattedValue.ToString();
}
sendingCB.SelectedIndexChanged -= new EventHandler(LastColumnComboSelectionChanged);
}
#endregion
}
You can create different instances of the UserControl, I usually do so.
MyUserControl myUc MyUserControl = new ();
public MyUserControl CALLED= null;
private void FrmXXXXX_Load(object sender, EventArgs e)
{
MyUserControl uc = new MyUserControl ();
uc.VALUE = this.VALUE;
uc.CALLER = this;
uc.Parent = pnlMain;
uc.Dock = DockStyle.Fill;
}
This way you can create many different UserControl equal but different instances in memory and behavior
I'm trying to add an array of strings that holds information about people to a ListBox but i cant get it to show anything and i really dont know why.
This is the first class that is called when the button to add contacts to the list is clicked.
public partial class MainForm : Form
{
private ContactManager m_contacts;
public MainForm()
{
InitializeComponent();
m_contacts = new ContactManager();
InitializeGUI();
}
private void InitializeGUI()
{
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtStreet.Text = string.Empty;
txtCity.Text = string.Empty;
txtZipCode.Text = string.Empty;
cmbCountry.Items.AddRange(Enum.GetNames(typeof(Countries)));
cmbCountry.DropDownStyle = ComboBoxStyle.DropDownList;
cmbCountry.SelectedIndex = (int)Countries.Sverige;
UpdateGUI();
}
private bool ReadInput(out Contact contact)
{
// skapar ett lokalt objekt av Contact-klassen
contact = new Contact();
// Lägger in ReadAdress till ett objekt i klassen Adress.
Address adr = ReadAddress();
contact.AddressData = adr; // skickar adress till contact-objekt
//bool readNameOK = ReadName();
// ReadName är OK så skickas det till AddContact.
if (ReadName())
{
m_contacts.AddContact(contact);
}
return ReadName();
} // ReadInput
private bool ReadName()
{
Contact contact = new Contact();
contact.FirstName = txtFirstName.Text;
contact.LastName = txtLastName.Text;
bool firstname = false;
bool lastname = false;
if (!InputUtility.ValidateString(contact.FirstName))
{
MessageBox.Show("You must enter a first name with atleast one character (not a blank)", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
txtFirstName.Focus();
txtFirstName.Text = " ";
txtFirstName.SelectAll();
firstname = false;
}
else if (!InputUtility.ValidateString(contact.LastName))
{
MessageBox.Show("You must enter a last name with atleast one character (not a blank)", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
txtLastName.Focus();
txtLastName.Text = " ";
txtLastName.SelectAll();
lastname = false;
}
return firstname && lastname;
}
private Address ReadAddress()
{
Address address = new Address();
address.Street = txtStreet.Text;
address.City = txtCity.Text;
address.ZipCode = txtZipCode.Text;
address.Country = (Countries)cmbCountry.SelectedIndex;
return address;
}
private void button1_Click(object sender, EventArgs e)
{
Contact contact;
if (ReadInput(out contact))
{
UpdateGUI();
}
}
private void UpdateGUI()
{
lstContacts.Items.Clear();
lstContacts.Items.AddRange(m_contacts.GetContactsInfo());
lblCount.Text = m_contacts.Count().ToString();
}
private void lstContacts_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateContactInfoFromRegistry();
}
private void UpdateContactInfoFromRegistry()
{
Contact contact = m_contacts.GetContact(lstContacts.SelectedIndex);
cmbCountry.SelectedIndex = (int)contact.AddressData.Country;
txtFirstName.Text = contact.FirstName;
txtLastName.Text = contact.LastName;
txtCity.Text = contact.AddressData.City;
txtStreet.Text = contact.AddressData.Street;
txtZipCode.Text = contact.AddressData.ZipCode;
}
}
This class then calls this class
public class ContactManager
{
private List<Contact> m_contactRegistry;
public ContactManager()
{
m_contactRegistry = new List<Contact>();
}
public int Count()
{
int count = m_contactRegistry.Count();
return count;
}
public bool CheckIndex(int index)
{
if (index >= 0 && index < m_contactRegistry.Count())
return true;
else return false;
}
public bool AddContact(string firstName, string lastName, Address addressIn)
{
Contact contactObj = new Contact();
bool result = false;
if (!result)
{
contactObj.FirstName = firstName;
contactObj.LastName = lastName;
contactObj.AddressData = addressIn;
m_contactRegistry.Add(contactObj);
result = true;
}
return result;
}
public bool AddContact(Contact contactIn)
{
if (contactIn == null)
{
return false;
}
else
{
m_contactRegistry.Add(contactIn);
return true;
}
}
public bool changeContact(Contact contactIn, int index)
{
if (CheckIndex(index))
{
Contact contact = (Contact)m_contactRegistry[index];
//contact.ToString = contactIn;
return true;
}
else return false;
}
public bool DeleteContact(int index)
{
if (CheckIndex(index))
{
m_contactRegistry.RemoveAt(index);
return true;
}
else return false;
}
public Contact GetContact(int index)
{
if (!CheckIndex(index))
return null;
else return m_contactRegistry[index];
}
public string[] GetContactsInfo()
{
string[] strInfoStrings = new string[m_contactRegistry.Count];
int i = 0;
foreach (Contact contactObj in m_contactRegistry)
{
strInfoStrings[i++] = contactObj.ToString();
}
return strInfoStrings;
}
}
Any help regarding why the arrays wont show up in the listbox would be much appriciated, thanks.
Your ReadName() always returns false, there for it never adds the contacts.
EDIT:
A clearer code
private Contact ReadInput()
{
Contact contact = new Contact();
contact.FirstName = txtFirstName.Text;
contact.LastName = txtLastName.Text;
contact.AddressData = new Address
{
Street = txtStreet.Text,
City = txtCity.Text,
ZipCode = txtZipCode.Text,
Country = (Countries) cmbCountry.SelectedIndex
};
return contact;
}
private bool ValidateContact(Contact contact)
{
if ( !InputUtility.ValidateString( contact.FirstName ) )
{
MessageBox.Show( "You must enter a first name with atleast one character (not a blank)", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error );
txtFirstName.Focus();
txtFirstName.Text = " ";
txtFirstName.SelectAll();
return false;
}
else if ( !InputUtility.ValidateString( contact.LastName ) )
{
MessageBox.Show( "You must enter a last name with atleast one character (not a blank)", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error );
txtLastName.Focus();
txtLastName.Text = " ";
txtLastName.SelectAll();
return false;
}
return true;
}
private void button1_Click( object sender, EventArgs e )
{
Contact contact = ReadInput();
if ( ValidateContact( contact ) )
{
m_contacts.AddContact(contact);
UpdateGUI();
}
}