我正在使用C#创建一个Windows窗体应用程序,以便将扫描到文本框中的跟踪号码保存到数据库中。我有设计的表单和数据库设置,但我无法弄清楚如何将表单保存到数据库。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PackageTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void confirmBtn_Click(object sender, EventArgs e)
{
try
{
//parses tracking number to determine the shipping method/carrier. Places result in shipType text box
shipTypeTextBox.Text = determineShipType(trackingNumTextBox.Text);
//save to DB
this.Validate();
this.packagesBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.packagesDataSet);
//display info sent to DB
AutoClosingMessageBox.Show("Tracking Number: " + trackingNumTextBox.Text + "\n" +
"Ship Type: " + shipTypeTextBox.Text + "\n" +
"Ship Date: " + dateDateTimePicker.Value, "Test", 1000);
//clear fields to ready form for next scan
trackingNumTextBox.Text = "";
shipTypeTextBox.Text = "";
}
catch(IndexOutOfRangeException err)
{
string errMess = string.Format("Error: {0}", err.Source);
MessageBox.Show( errMess, "Error");
}
}
public string determineShipType(string tNum)
{
if (tNum[0] == '1')
{
if (tNum.Substring(8, 2) == "YW")
return "UPS Surepost";
return "UPS";
}
if (tNum[0] == '4')
{
if(tNum.Substring(8, 4) == "9400")
return "USPS FCM";
if (tNum.Substring(8, 4) == "9405")
return "USPS Priortiy Mail";
}
return "Unknown Ship Type";
}
}
}
我做错了什么?
编辑:我没有编写Validate()方法。我在另一个使用BindingNavigation控件的应用程序中复制了由VS自动生成的代码。以下是我右键单击它并使用Go To Definition:
时显示的代码//
// Summary:
// Verifies the value of the control losing focus by causing the System.Windows.Forms.Control.Validating
// and System.Windows.Forms.Control.Validated events to occur, in that order.
//
// Returns:
// true if validation is successful; otherwise, false. If called from the System.Windows.Forms.Control.Validating
// or System.Windows.Forms.Control.Validated event handlers, this method will
// always return false.
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public bool Validate();
当我将Packages表从我的DB拖到表单上时,这个代码全部由VS生成:
private PackagesDataSet packagesDataSet;
private System.Windows.Forms.BindingSource packagesBindingSource;
private PackagesDataSetTableAdapters.PackagesTableAdapter packagesTableAdapter;
private PackagesDataSetTableAdapters.TableAdapterManager tableAdapterManager;