显示基于GridView数据的新表单

时间:2009-08-31 23:03:56

标签: c# .net winforms gridview currencymanager

我的主窗体MainForm上有一个GridView,radGvA133s。我希望能够双击GridView的一行并打开一个新表单A133Form,以允许编辑所选行。

这是双击代码:

    private void radGvA133s_DoubleClick(object sender, EventArgs e)
    {
        A133 oA133 = (A133)A133BindingSource.CurrencyManager.List[A133BindingSource.CurrencyManager.Position];
        A133Form oA133Form = new A133Form();
        oA133Form.NewA133 = oA133;
        oA133Form.IsNew = false;
        oA133Form.ShowDialog(this);
        //On return - if not cancelled, then continue
        if (oA133Form.Cancelled != true)
        {
            this.radGvA133s.Refresh();
        }
        oA133Form.Dispose();
        oA133Form = null;
    }

这是A133Form代码:

    public partial class A133Form : Form
{   
    public A133Form()
    {
        InitializeComponent();
    }

    private bool _IsNew;
    public bool IsNew
    {
        get
        {
            return _IsNew;
        }
        set
        {
            _IsNew = value;
        }
    }

    private bool _Cancelled;
    public bool Cancelled
    {
        get
        {
            return _Cancelled;
        }
        set
        {
            _Cancelled = value;
        }
    }

    private A133 _newA133 = new A133();
    public A133 NewA133
    {
        get
        {
            return _newA133;
        }
        set
        {
            _newA133 = value;
        }
    }

    private void A133Form_Load(object sender, EventArgs e)
    {
        A133DB A133DB = new A133DB();

        DataTable dtRSNs = A133DB.GetRSNList();
        DataRow drFirstItem = dtRSNs.NewRow();

        radComboRSN.DataSource = dtRSNs;
        drFirstItem["rsn_id"] = "0";
        drFirstItem["rsn_name"] = "";
        dtRSNs.Rows.InsertAt(drFirstItem, 0);
        radComboRSN.ValueMember = "rsn_id";
        radComboRSN.DisplayMember = "rsn_name";

        //Set databindings
        radComboRSN.DataBindings.Add(new Binding("Text", NewA133, "RSN", true, DataSourceUpdateMode.OnPropertyChanged));
        radTxtSubcontractor.DataBindings.Add(new Binding("Text", NewA133, "Subcontractor", true, DataSourceUpdateMode.OnPropertyChanged));
        radMTxtCFDANumber.DataBindings.Add(new Binding("Text", NewA133, "CFDANumber", true, DataSourceUpdateMode.OnPropertyChanged));
        radCbIncludeCFDA.DataBindings.Add(new Binding("Checked", NewA133, "IncludeCFDA", true, DataSourceUpdateMode.OnPropertyChanged));
        radMTxtYear.DataBindings.Add(new Binding("Text", NewA133, "sYear", true, DataSourceUpdateMode.OnPropertyChanged));
        radTxtFedAward.DataBindings.Add(new Binding("Text", NewA133, "FedAward", true, DataSourceUpdateMode.OnPropertyChanged));
        radCbExceeds.DataBindings.Add(new Binding("Checked", NewA133, "Exceeds", true, DataSourceUpdateMode.OnPropertyChanged));
        radDTPDateMHDReceived.DataBindings.Add(new Binding("Value", NewA133, "DateMHDReceived", true, DataSourceUpdateMode.OnPropertyChanged));
        radDTPPeriodEnding.DataBindings.Add(new Binding("Value", NewA133, "PeriodEnding", true, DataSourceUpdateMode.OnPropertyChanged));
        radDTPDateAudited.DataBindings.Add(new Binding("Value", NewA133, "DateAudited", true, DataSourceUpdateMode.OnPropertyChanged));
        radDTPForwardDate.DataBindings.Add(new Binding("Value", NewA133, "ForwardDate", true, DataSourceUpdateMode.OnPropertyChanged));
        radTxtSAOPerson.DataBindings.Add(new Binding("Text", NewA133, "SAOPerson", true, DataSourceUpdateMode.OnPropertyChanged));
    }

    private void radBtnCancel_Click(object sender, EventArgs e)
    {
        this.Cancelled = true;
        this.Close();
    }

    private void radBtnSave_Click(object sender, EventArgs e)
    {
        this.Cancelled = false;
        bool bValid = true;

        foreach(Control control in this.Controls)
        {
            if (Convert.ToString(control.Tag) == "Required")
            {
                bool bMissingInfo = false;
                if (control is RadDateTimePicker)
                {
                    RadDateTimePicker dtp = control as RadDateTimePicker;

                    if (dtp.Value.ToString() == "1/1/0001 12:00:00 AM")
                    {
                        bMissingInfo = true;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(control.Text))
                    {
                        bMissingInfo = true;
                    }
                }
                if (bMissingInfo == true)
                {
                    errorProvider1.SetError(control, "* Required Field");
                    bValid = false;
                }
                else
                {
                    errorProvider1.SetError(control, "");
                }
            }
        }
        if (bValid == true)
        {
            bool bSaved = NewA133.SaveData();
            if (bSaved == true)
            {
                this.Close();
            }
            else
            {
                MessageBox.Show("There was an error saving the data!  If this continues, please contact technical assistance.",
                                "Error Saving Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        else
        {
            MessageBox.Show("The information you have entered is incomplete.  Please fill out all required fields.", 
                            "Missing Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
}

最后,这是A133类代码:

#region A133 Collection

public class A133Collection : BindingListView<A133>
{
    public A133Collection() : base()
    {
    }

    public A133Collection(List<A133> a133s) : base(a133s)
    {
    }

    public A133Collection(DataTable dt)
    {
        foreach(DataRow oRow in dt.Rows)
        {
            A133 a = new A133(oRow);
            this.Add(a);
        }
    }

    private int FindMaxId()
    {
        int maxId = -1;
        foreach(A133 a in this)
        {
            if (a.A133Id > maxId)
            {
                maxId = a.A133Id;
            }
        }
        return maxId;
    }
}

#endregion

#region A133 Class

///<summary>
///Class:   A133
///Desc:    Manages a single A133 business object
///         Note - 4 states for the object: Unchanged, Added, Deleted, Modified
///             Added flags that a brand new object was added; set prior to db insert
///             Deleted flags that the object was deleted; set after db delete
///             Unchanged is default state
///             Modified flags that props have changed
///             >> The IsDirty indicator looks to see if the object is "modified" or "added"
///             since these are pre-database flags
///</summary>

public class A133 : INotifyPropertyChanged, IEditableObject, IDataErrorInfo
{
    //Declare internal class collection object
    private A133Collection _A133s = new A133Collection();

    //Declare internal class objects
    private MHDFMS.BusinessLogic.A133DB _DB = new A133DB();

    //Declare internal class props
    private int _A133Id;
    private string _RSN;
    private string _Subcontractor;
    private string _CFDANumber;
    private string _IncludeCFDA;
    private string _Year;
    private string _FedAward;
    private string _Exceeds;
    private string _DateMHDReceived;
    private string _PeriodEnding;
    private string _DateAudited;
    private string _ForwardDate;
    private string _SAOPerson;
    private int _OldA133Id;
    private string _OldRSN;
    private string _OldSubcontractor;
    private string _OldCFDANumber;
    private string _OldIncludeCFDA;
    private string _OldYear;
    private string _OldFedAward;
    private string _OldExceeds;
    private string _OldDateMHDReceived;
    private string _OldPeriodEnding;
    private string _OldDateAudited;
    private string _OldForwardDate;
    private string _OldSAOPerson;
    private bool _Editing;
    private string _Error = string.Empty;
    private EntityStateEnum _EntityState;
    private Hashtable _PropErrors = new Hashtable();

    private void FirePropertyChangeNotification(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    public A133()
    {
        this.EntityState = EntityStateEnum.Unchanged;
    }

    public A133(DataRow dr)
    {
        //Populates the business object item from a data row
        this.A133Id = Convert.ToInt32(dr["a133_id"]);
        this.RSN = dr["rsn"].ToString();
        this.Subcontractor = dr["subcontractor"].ToString();
        this.CFDANumber = dr["cfda_no"].ToString();
        this.IncludeCFDA = dr["include_cfda"].ToString();
        this.sYear = dr["year"].ToString();
        this.FedAward = dr["fed_award"].ToString();
        this.Exceeds = dr["exceeds"].ToString();
        if (dr["date_mhd_received"] != null)
        {
            this.DateMHDReceived = Convert.ToDateTime(dr["date_mhd_received"]).ToShortDateString();
        }
        if (dr["period_ending"] != null)
        {
            this.PeriodEnding = Convert.ToDateTime(dr["period_ending"]).ToShortDateString();
        }
        if (dr["date_audited"] != null)
        {
            this.DateAudited = Convert.ToDateTime(dr["date_audited"]).ToShortDateString();
        }
        if (dr["forward_date"] != null)
        {
            this.ForwardDate = Convert.ToDateTime(dr["forward_date"]).ToShortDateString();
        }
        this.SAOPerson = dr["sao_person"].ToString();
        this.EntityState = EntityStateEnum.Unchanged;
    }

    #region Public Methods/Constructors

    public bool SaveData()
    {
        bool bSaved = false;
        if (this.A133Id == 0)
            {
            bSaved = _DB.SaveA133Data(this);
        }
        else
        {
            bSaved = _DB.SaveA133Data(this);
        }
        if (bSaved == true)
        {
            this.EntityState = EntityStateEnum.Unchanged;
        }
        return bSaved;
    }

    public bool Delete()
    {
        bool bSaved = _DB.SaveA133AsInactive(this);
        if (bSaved == true)
        {
            this.EntityState = EntityStateEnum.Deleted;
        }
        return bSaved;
    }

    public Int32 A133Id
    {
        get
        {
            return _A133Id;
        }
        set
        {
            _A133Id = value;
        }
    }

    public string RSN
    {
        get
        {
            return _RSN;
        }
        set
        {
            _RSN = value;
            FirePropertyChangeNotification("RSN");
        }
    }

    public string Subcontractor
    {
        get
        {
            return _Subcontractor;
        }
        set
        {
            _Subcontractor = value;
            FirePropertyChangeNotification("Subcontractor");
        }
    }

    public string CFDANumber
    {
        get
        {
            return _CFDANumber;
        }
        set
        {
            _CFDANumber = value;
            FirePropertyChangeNotification("CFDANumber");
        }
    }

    public string IncludeCFDA
    {
        get
        {
            return _IncludeCFDA;
        }
        set
        {
            _IncludeCFDA = value;
            FirePropertyChangeNotification("IncludeCFDA");
        }
    }

    public string sYear
    {
        get
        {
            return _Year;
        }
        set
        {
            _Year = value;
            FirePropertyChangeNotification("sYear");
        }
    }

    public string FedAward
    {
        get
        {
            return _FedAward;
        }
        set
        {
            _FedAward = value;
            FirePropertyChangeNotification("FedAward");
        }
    }

    public string Exceeds
    {
        get
        {
            return _Exceeds;
        }
        set
        {
            _Exceeds = value;
            FirePropertyChangeNotification("Exceeds");
        }
    }

    public string DateMHDReceived
    {
        get
        {
            return _DateMHDReceived;
        }
        set
        {
            _DateMHDReceived = value;
            FirePropertyChangeNotification("DateMHDReceived");
        }
    }

    public string PeriodEnding
    {
        get
        {
            return _PeriodEnding;
        }
        set
        {
            _PeriodEnding = value;
            FirePropertyChangeNotification("PeriodEnding");
        }
    }

    public string DateAudited
    {
        get
        {
            return _DateAudited;
        }
        set
        {
            _DateAudited = value;
            FirePropertyChangeNotification("DateAudited");
        }
    }

    public string ForwardDate
    {
        get
        {
            return _ForwardDate;
        }
        set
        {
            _ForwardDate = value;
            FirePropertyChangeNotification("ForwardDate");
        }
    }

    public string SAOPerson
    {
        get
        {
            return _SAOPerson;
        }
        set
        {
            _SAOPerson = value;
            FirePropertyChangeNotification("SAOPerson");
        }
    }

    public Boolean IsDirty
    {
        get
        {
            return ((this.EntityState != EntityStateEnum.Unchanged) || (this.EntityState != EntityStateEnum.Deleted));
        }
    }

    public enum EntityStateEnum
    {
        Unchanged,
        Added,
        Deleted,
        Modified
    }

    public A133Collection A133s
    {
        get
        {
            return _A133s;
        }
    }

    void IEditableObject.BeginEdit()
    {
        if (!_Editing)
        {
            _OldA133Id = _A133Id;
            _OldRSN = _RSN;
            _OldSubcontractor = _Subcontractor;
            _OldCFDANumber = _CFDANumber;
            _OldIncludeCFDA = _IncludeCFDA;
            _OldYear = _Year;
            _OldFedAward = _FedAward;
            _OldExceeds = _Exceeds;
            _OldDateMHDReceived = _DateMHDReceived;
            _OldPeriodEnding = _PeriodEnding;
            _OldDateAudited = _DateAudited;
            _OldForwardDate = _ForwardDate;
            _OldSAOPerson = _SAOPerson;
        }
        this.EntityState = EntityStateEnum.Modified;
        _Editing = true;
    }

    void IEditableObject.CancelEdit()
    {
        if (_Editing)
        {
            _A133Id = _OldA133Id;
            _RSN = _OldRSN;
            _Subcontractor = _OldSubcontractor;
            _CFDANumber = _OldCFDANumber;
            _IncludeCFDA = _OldIncludeCFDA;
            _Year = _OldYear;
            _FedAward = _OldFedAward;
            _Exceeds = _OldExceeds;
            _DateMHDReceived = _OldDateMHDReceived;
            _PeriodEnding = _OldPeriodEnding;
            _DateAudited = _OldDateAudited;
            _ForwardDate = _OldForwardDate;
            _SAOPerson = _OldSAOPerson;
        }
        this.EntityState = EntityStateEnum.Unchanged;
        _Editing = false;
    }

    void IEditableObject.EndEdit()
    {
        _Editing = false;
    }

    public EntityStateEnum EntityState
    {
        get
        {
            return _EntityState;
        }
        set
        {
            _EntityState = value;
        }
    }

    string IDataErrorInfo.Error
    {
        get
        {
            return _Error;
        }
    }

    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            return (string)_PropErrors[columnName];
        }
    }

    private void DataStateChanged(EntityStateEnum dataState, string propertyName)
    {
        //Raise the event
        if (PropertyChanged != null && propertyName != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        //If the state is deleted, mark it as deleted
        if (dataState == EntityStateEnum.Deleted)
        {
            this.EntityState = dataState;
        }
        if (this.EntityState == EntityStateEnum.Unchanged)
        {
            this.EntityState = dataState;
        }
    }

    #endregion
}

#endregion

不幸的是,当我双击GridView时,我收到此错误:“InvalidCastException未处理。无法将类型为'System.Data.DataRowView'的对象强制转换为'MHDFMS.BusinessLogic.A133'”

此错误发生在双击事件的第一行。

我在这里不知所措,已经把头发拉了一段时间。我错过了一些明显的东西吗是否有更简单(或更好!)的方式来实现我想要的结果?

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

试试这个:

DataRowView currentRow = A133BindingSource.CurrencyManager.List[A133BindingSource.CurrencyManager.Position] as DataRowView;
A133Form oA133Form = new A133Form();
oA133Form.NewA133 = new A133(currentRow.Row);

答案 1 :(得分:1)

您忘记发布导致异常的事件处理程序......;)

但问题的根源似乎很明显 - 你从属性网格中得到一个DataRowView对象,并尝试将它(可能通过分配给一个变量)转换为A133你可能想要{ {1}}。