在Windows窗体和数据库之间传递值

时间:2017-02-02 14:42:33

标签: c# winforms visual-studio

我在尝试为大学作业构建Windows表单解决方案时遇到了问题,并希望有人可以指出我的错误。

解决方案是关于移动商店。我有两个类,Apple和Android表单。我需要读取数据库表中的数据,将条目分类为Android或Apple手机,然后在表单加载时在列表中显示所有手机。

我可以成功地对手机进行分类,但在尝试阅读这些条目时,我总是在表单上的列表中输入两次相同的条目,而第二个条目根本没有出现。

我知道在进行连接时我犯了一个很大的愚蠢错误,但我找不到它!。

这是我的代码:

public abstract class MobilePhone {
    private Int32 phoneID;
    private string operatingSystem;
    private string make;
    private string model;
    public enum Condition { Poor, Fair, Good, Mint };
    private Condition condition;
    private decimal originalPrice;
    private DateTime datePurchase;
    private string description;
    private clsDataConnection dbConnection;

    //constructor
    public MobilePhone(string make, string model, decimal originalPrice, DateTime datePurchase, Condition condition, string description) {
        this.make = make;
        this.model = model;
        this.originalPrice = originalPrice;
        this.datePurchase = datePurchase;
        this.condition = condition;
        this.description = description;
    }

不完整,但那是相关的:

public class ApplePhone : MobilePhone {
    decimal ApproxValue;
    public ApplePhone(string make, string model, decimal originalPrice, DateTime datePurchase, Condition condition, string description)
        : base(make, model, originalPrice, datePurchase, condition, description) {
    }

Android类是相同的,但具有不同的其他功能。

class Shop {
    clsDataConnection dbConnection;
    const int NotAdded = -1;  // invalid primary key
    private string name;
    private decimal ApproxValue;
    private Int32 phoneID;
    private string operatingSystem;
    private string make;
    private string model;
    private MobilePhone.Condition condition;
    private decimal originalPrice;
    private DateTime datePurchase;
    private string description;
    Int32 Index;
    private List<MobilePhone> phonesForSale;

    //constructor
    public Shop(string name) {
        this.name = name;
    }

    MobilePhone phone;

    public void SelectAll() {
        dbConnection = new clsDataConnection();
        dbConnection.Execute("SellectAllPhones");
    }

    public void FilterByOperatingSystem(string operatingSystem) {
        dbConnection = new clsDataConnection();
        dbConnection.AddParameter("@OperatingSystem", operatingSystem);
        dbConnection.Execute("FilterByOperatingSystem");
    }

    public Int32 Count {
        get {
            //return the count of records
            return dbConnection.Count;
        }
    }

    public string DescribeCurrentPhone(int Index) {
        Int32 phoneID;
        string make;
        string model;
        MobilePhone.Condition condition;
        decimal originalPrice;
        DateTime datePurchase;
        string description;

        phoneID = Convert.ToInt32(phonesForSale[Index].PhoneID);
        make = Convert.ToString(phonesForSale[Index].Make);
        model = Convert.ToString(phonesForSale[Index].Model);
        condition = phonesForSale[Index].GetCondition;
        originalPrice = Convert.ToDecimal(phonesForSale[Index].OriginalPrice);
        datePurchase = Convert.ToDateTime(phonesForSale[Index].DatePurchased);
        description = Convert.ToString(phonesForSale[Index].Description);
        //set up a new object of class list item             
        string listItemText = make + " " + "|" + " " + model + " " + "|" + " " + condition + " " + "|" + " " + "£" + Math.Round(originalPrice, 2) + " " + "|" + " " + datePurchase.ToShortDateString() + " " + "|" + " " + description;
        return listItemText;
    }

    public List<MobilePhone> Allphones {
        get {
            phonesForSale = new List<MobilePhone>();
            int count = Count;
            Index = 0;
            while (Index < count) {
                phoneID = Convert.ToInt32(dbConnection.DataTable.Rows[Index]["PhoneId"]);
                operatingSystem = Convert.ToString(dbConnection.DataTable.Rows[Index]["OperatingSystem"]);
                make = Convert.ToString(dbConnection.DataTable.Rows[Index]["Make"]);
                model = Convert.ToString(dbConnection.DataTable.Rows[Index]["Model"]);
                string conditionString = Convert.ToString(dbConnection.DataTable.Rows[Index]["Condition"]);
                originalPrice = Convert.ToInt32(dbConnection.DataTable.Rows[Index]["OriginalPrice"]);
                datePurchase = Convert.ToDateTime(dbConnection.DataTable.Rows[Index]["DatePurchased"]);
                description = Convert.ToString(dbConnection.DataTable.Rows[Index]["Description"]);
                // Set Condition
                if (conditionString == "Poor") {
                    condition = MobilePhone.Condition.Poor;
                } else if (conditionString == "Fair") {
                    condition = MobilePhone.Condition.Fair;
                } else if (conditionString == "Good") {
                    condition = MobilePhone.Condition.Good;
                } else if (conditionString == "Mint") {
                    condition = MobilePhone.Condition.Mint;
                }
                //check Operating System
                if (operatingSystem == "IOS") {
                    phone = new ApplePhone(make, model, originalPrice, datePurchase, condition, description);
                    //ApproxValue = ApplePhone.CalculateApproximateValue();
                } else if (operatingSystem == "Android") {
                    phone = new AndroidPhone(make, model, originalPrice, datePurchase, condition, description);
                    //ApproxValue = AndroidPhone.CalculateApproximateValue();
                }
                Index++;
                phonesForSale.Add(phone);
            }
            return phonesForSale;
        }
    }

表单代码是:

public partial class FormMain : Form {
    public FormMain() {
        InitializeComponent();
        Shop shop = new Shop("");
    }

    private void FormMain_Load(object sender, EventArgs e) {
        DisplayItems("");
    }

    protected int DisplayItems(string operatingSystem) {
        Shop MyShop = new Shop("");
        Int32 RecordCount;
        Int32 Index = 0;
        Int32 PID;

        if (operatingSystem != "") {
            MyShop.FilterByOperatingSystem(operatingSystem);
        } else {
            MyShop.SelectAll();
        }

        RecordCount = MyShop.Count;
        ArrayList MyPhones = new ArrayList();
        while (Index < RecordCount) {
            // I Suspect this line is the problem but don't know how to fix it
            PID = MyShop.Allphones[Index].PhoneID
            string listItemText = MyShop.DescribeCurrentPhone(PID);
            //add the new item to the list
            MyPhones.Add(listItemText);
            //increment the index
            Index++;
        }
        listBox1.DataSource = MyPhones;
        return RecordCount;
    }

我不习惯连接数据库,所以任何建议都会有所帮助!

2 个答案:

答案 0 :(得分:0)

您所做的数据库连接替代方案的示例如下

  List<MyPhone> myIPhoneList = new List<Myphone>();
   List<MyPhone> myAndroidList = new List<Myphone>();

SqlConnection myDBConnection = new SqlConnection("MyConnectionString"); //DB Connection
            SqlCommand dbCommand = new SqlCommand("SelectAllPhones"); //Stored Procedure
            SqlDataReader recordReader = dbCommand.ExecuteReader(); //Execute

            //Read records return in to phone objects
            while (recordReader.Read()) {
                var phoneField1 = recordReader["PhoneField1FromDatabase"];
                var phoneField2 = recordReader["PhoneField2FromDatabase"];
                //etc...

                var myPhone = new MyPhone();
                myPhone.Name = phoneField1;
                //etc...
                if (myPhone.OS == "iPhone")
                 myIPhoneList.Add(myPhone);

               if (myPhone.OS = "Android")
                 myAndroidList.Add(myPhone);
            }

答案 1 :(得分:0)

只是扭转了车轮的答案,

我个人对存储过程进行过滤。

SqlCommand dbCommand = new SqlCommand(&#34; SelectAllPhones&#34;); //存储过程

变得像:

Hi, Test User! How are you today? bad
 m _ h h!

仅因为每个类拖动两组电话数据(android / iphone)的点数非常少。您也可以只撤回所需的数据。

当然,Stored-Proc需要更新以满足参数。

像这样的东西: AND PhoneOS = @OS

需要附加到您的SQL条件。

clsDataConnection dbConnection;我不知道 - 这是第三方图书馆还是你写过的课程,不包括在内?

using (SqlConnection conn = new SqlConnection())
{
  using (SqlCommand cmd = new SqlCommand("SelectAllPhones", conn))
  {
    cmd.Parameters.Add(new SqlParameter() { ParameterName = "@OS", SqlDbType = SqlDbType.VarChar, Direction = ParameterDirection.Input, Value = phoneOS });
    cmd.CommandType = CommandType.StoredProcedure;

    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())
    {
      // load your data...

    }

  }
}

dbConnection.Count似乎非常不标准。不会读取,就好像您正在尝试获取行数,更多是连接数 - 这在此处无效。

dbConnection.DataTables [0] .Rows.Count;这将是一种使用现有代码确定行的更好方法,因为它现在读取就好像你计算数据库连接的数量而不是你的后续 - 并且如果使用我或者轮子你将不会多余需要事先知道你要处理多少行。