Asp.net无法将类型'string'转换为System.Data.DataRowView“

时间:2014-04-12 11:22:08

标签: c# asp.net datagridview

我是asp.net c#的新手 我有点问题,希望有人可以帮帮我。

我想要做的是从下拉列表中使用c#自动填充asp.net中的一些文本框,这样当他们点击列表并选择零售时,文本框将自动填充来自访问数据库

以下是我的代码到目前为止有点乱,但那是因为我还在写它。

namespace ChocoMamboAsp
{
    public partial class  SalesOrderForm : System.Web.UI.UserControl
    {
        SalesOrder _order = null;


        protected void Page_Load(object sender, EventArgs e)
        {
            if (System.Web.HttpContext.Current.Session["SalesOrderID"] == null)
            {
                _order = new SalesOrder();
                populateCustomerCombo();
                populateEmployeeCombo();
                populateProductCombo();

            }
            else
            {
                _order = new SalesOrder(long.Parse(System.Web.HttpContext.Current.Session["SalesOrderID"].ToString()));
                populateCustomerCombo();
                populateEmployeeCombo();
                populateProductCombo();

                displayRecord();


           }

        }

        #region Mutators
        /// <summary>
        /// Pre-Condtion:   Event Call
        /// Post-Condition: calculates the item total
        /// Description:    Calculates the line total for each item in the grid list
        /// </summary>
        private void calculateLineTotal()
        {
            int intQty = 0;
            decimal decPrice = 0.0M;
            var total = 0;
            foreach (GridViewRow row in dgvOrderLine.Rows)
            {
                var numberLabel = row.FindControl("LineTotal") as Label;
                int number;
                if (int.TryParse(numberLabel.Text, out number))
                {
                    total += number;
                }
            }

            decimal decLineTotal = decPrice * intQty;
            txtSubTotal.Text = decLineTotal.ToString("c2");
            calculateGrandTotal();
        }

        /// <summary>
        /// Pre-Condtion:   Events call
        /// Post-Condition: Calculate the total of all the items
        /// Description:    This will calculate the total of all the items in the list area.
        /// </summary>
        private void calculateGrandTotal()
        {
            try
            {
                decimal decGrandTotal = decimal.Parse(_order.getOrderLinesTable().Compute
                                                      ("Sum(LineTotal)", "").ToString());
                lblTotal.Text = decGrandTotal.ToString("c2");
            }
            catch (FormatException)
            {
                //this exception will occur if tblOrderLine is empty which we can safely ignore
            }
        }


        #endregion

        protected void btnInsert_Click(object sender, EventArgs e)
        {

                assignChildData();
                _order.OrderLineClass.addNewRecord();
                calculateGrandTotal();
                emptyControls();

        }

        #region Accessors
        /// <summary>
        /// Pre-Condition: Second Constructor Call 
        /// Post-Condition: Gettes the information from the class getters and setters 
        /// Description: This method gets all the information relating to the table database that has been used.
        /// </summary>     
        private void displayRecord()
        {
            cboRetailer.SelectedValue = _order.RetailerID.ToString();
            dtpSalesOrder.Text = _order.SalesDate.ToString();
            cboSalesAgent.SelectedValue = _order.EmployeeID.ToString();
            txtRetailerAddress.Text = _order.RetailerAddress;
            txtRetailerPhone.Text = _order.RetailerPhone;
            lblTotal.Text = _order.SaleTotal.ToString("c2");
            dgvOrderLine.DataSource = _order.getOrderLinesTable();
            dgvOrderLine.DataBind();

            System.Diagnostics.Debug.WriteLine(_order.getOrderLinesTable());
        }
        /// <summary>
        /// Pre-Condition:  Construtor's call
        /// Post-Condition:Populates the combo box with the requested information
        /// Description: This method uses the method from the class in order to populate the combo box with the selcted information
        ///              To display one or more Items.
        /// </summary>
        private void populateCustomerCombo()
        {
            cboRetailer.DataSource = _order.getCustomers();
            cboRetailer.DataValueField = "RetailerID";
            cboRetailer.DataTextField = "RetailerName";
            cboRetailer.DataBind();

        }
        /// <summary>
        /// Pre-Condition:  Construtor's call
        /// Post-Condition:Populates the combo box with the requested information
        /// Description: This method uses the method from the class in order to populate the combo box with the selcted information
        ///              To display one or more Items.
        /// </summary>
        private void populateEmployeeCombo()
        {
            cboSalesAgent.DataSource = _order.getEmployee();
            cboSalesAgent.DataValueField = "EmployesID";
            cboSalesAgent.DataTextField = "EmployeeFirstName";
            cboSalesAgent.DataBind(); 

        }
        /// <summary>
        /// Pre-Condition:  Construtor's call
        /// Post-Condition:Populates the combo box with the requested information
        /// Description: This method uses the method from the class in order to populate the combo box with the selcted information
        ///              To display one or more Items.
        /// </summary>
        private void populateProductCombo()
        {

            cboProducts.DataSource = _order.getProducts();
            cboProducts.DataTextField = "ProdustsName";
            cboProducts.DataValueField = "ProductsID";
            cboProducts.SelectedIndex = -1;//will make the combo box select nothing
            cboProducts.DataBind();

        }


        /// <summary>
        /// Pre-Condition:  Event method call
        /// Post-Condition: Empties fields
        /// Description:    Method used to empty all the fields
        /// </summary>
        private void emptyTopControls()
        {
            cboSalesAgent.SelectedIndex = -1;
            cboRetailer.SelectedIndex = -1;
            txtRetailerAddress.Text = "";
            txtRetailerPhone.Text = "";
        }

        //mutators
        /// <summary>
        /// Pre-Condition:  Event call Method
        /// Post-Condition: Empties the controls for the lower section
        /// Description:    This will empty the controls of the lower section so the user can in put another item 
        ///                 In side the DataTable of the gridView we are casting the datasource as a data table in order 
        ///                 for us to delete the information inside each of the rows of the data table.
        /// </summary>
        private void emptyControls()
        {
            cboProducts.SelectedIndex = -1;
            txtPrice.Text = "";
            txtQty.Text = "";
            txtSubTotal.Text = string.Empty;
            btnInsert.Enabled = true;
            btnUpdate.Enabled = false;
            dgvOrderLine.DataSource = _order.getOrderLinesTable();
        }
        /// <summary>
        /// Pre-Condtion:   Event Call
        /// Post-Condition: Send information to the list grid
        /// Description:    This method will send the infromation from the selection side into the display list
        /// </summary>
        private void assignChildData()
        {
            _order.OrderLineClass.ProductsID = long.Parse(cboProducts.SelectedValue.ToString());
            _order.OrderLineClass.Qty = long.Parse(txtQty.Text);
            _order.OrderLineClass.Price = decimal.Parse(txtPrice.Text.Substring
                                                          (txtPrice.Text.IndexOf('$') + 1));
            _order.OrderLineClass.SalesOrderID = _order.PKID;
            _order.OrderLineClass.LineTotal = decimal.Parse(txtSubTotal.Text);
            _order.OrderLineClass.ProdustsName = cboProducts.Text;
        }


        /// <summary>
        /// Pre-Condition:  Event Call
        /// Post-Condition: Assings informatin to the text/combo fields
        /// Description:    This is called when ever the fields have information that needs displayed
        /// </summary>
        private void assignData()
        {
            DateTime date = Convert.ToDateTime(dtpSalesOrder.Text);
            _order.RetailerID = long.Parse(cboRetailer.SelectedValue.ToString());
            _order.SalesDate =  date;
            _order.EmployeeID = long.Parse(cboSalesAgent.SelectedValue.ToString());
            _order.RetailerAddress = txtRetailerAddress.Text;
            _order.RetailerPhone = txtRetailerPhone.Text;
            _order.SaleTotal = decimal.Parse(lblTotal.Text.Substring
                                              (lblTotal.Text.IndexOf('$') + 1));
        }
        #endregion

        protected void cboRetailer_SelectedIndexChanged(object sender, EventArgs e)
        {

            DataRowView drvCost = (DataRowView)cboRetailer.SelectedValue;
            txtRetailerAddress.Text = drvCost["RetailerAddress"].ToString();
            txtRetailerPhone.Text = drvCost["RetailerPhone"].ToString();
        }
    }

1 个答案:

答案 0 :(得分:1)

cboRetailer.SelectedValue是一个字符串,您无法将其转换为DataRowView

您可以尝试这样的事情:

修改

如果getCustomers()返回一个数据表,你可以这样做:

protected void cboRetailer_SelectedIndexChanged(object sender, EventArgs e)
{
    var dt = _order.getCustomers();

    for (int i = 0; i < dt.Rows.Count; i++)
    {
        if (dt.Rows[i]["RetailerID"].ToString() == cboRetailer.SelectedValue)
        {
            txtRetailerAddress.Text = dt.Rows[i]["RetailerAddress"].ToString();
            txtRetailerPhone.Text = dt.Rows[i]["RetailerPhone"].ToString();

        }
    }

}

或者如果getCustomers()返回IEmunerable<Customer>,您可以这样做:

protected void cboRetailer_SelectedIndexChanged(object sender, EventArgs e)
{
    int retailerID = 0;
    if(int.TryParse(cboRetailer.SelectedValue, out retailerID) && retailerID > 0)
    {
        var retailer = _order.getCustomers().Where(x => x.RetailerID == retailerID).FirstOrDefault();
        if (retailer != null)
        {
            txtRetailerAddress.Text = retailer.RetailerAddress;
            txtRetailerPhone.Text = retailer.RetailerPhone;
        }
    }
}