C# 我正在创建帐单表单。我在gridview中添加了textbox和dropdownlist。现在在textbox1中,我想从数据库中获取价格。

C# 我正在创建帐单表单。我在gridview中添加了textbox和dropdownlist。现在在textbox1中,我想从数据库中获取价格。,c#,C#,我正在创建帐单表单。我在gridview中添加了textbox和dropdownlist。现在在textbox1中,我想从数据库中获取价格。那么如何在文本框1中获取价格?我试了很多,但都找不到解决办法 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http

我正在创建帐单表单。我在gridview中添加了textbox和dropdownlist。现在在textbox1中,我想从数据库中获取价格。那么如何在文本框1中获取价格?我试了很多,但都找不到解决办法

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <div>

        <asp:gridview ID="Gridview1"  runat="server"  ShowFooter="true"  
                                 AutoGenerateColumns="false"  
                                 OnRowCreated="Gridview1_RowCreated" 
           >  
        <Columns>  
            <asp:BoundField DataField="RowNumber" HeaderText="Medicine Id" />  
            <asp:TemplateField HeaderText="Medicine Name">  
                <ItemTemplate>  
               <asp:DropDownList ID="DropDownList3" runat="server" AppendDataBoundItems="true">
                <asp:ListItem Value="-1">Select</asp:ListItem>
            <asp:ListItem>crocin</asp:ListItem>
            <asp:ListItem>colgate</asp:ListItem>
            <asp:ListItem></asp:ListItem>
        </asp:DropDownList>
                 </ItemTemplate>  
            </asp:TemplateField>  
            <asp:TemplateField HeaderText="Quantity">  
                <ItemTemplate>  
                    <asp:DropDownList ID="DropDownList4" runat="server" AppendDataBoundItems="true">
                <asp:ListItem Value="-1">Select</asp:ListItem>
            <asp:ListItem>1</asp:ListItem>
            <asp:ListItem>2</asp:ListItem>
            <asp:ListItem>3</asp:ListItem>
            <asp:ListItem>4</asp:ListItem>
            <asp:ListItem></asp:ListItem>
        </asp:DropDownList>
                </ItemTemplate>  
            </asp:TemplateField>  
            <asp:TemplateField  HeaderText="Price">  
                <ItemTemplate>  
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
                </ItemTemplate>  
            </asp:TemplateField>  
            <asp:TemplateField HeaderText="Total">  
                <ItemTemplate>  
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> 
                </ItemTemplate>  
                <FooterStyle HorizontalAlign="Right" />  
                <FooterTemplate>  
                    <asp:Button ID="ButtonAdd" runat="server"   
                                         Text="Add New Row"   
                                         onclick="ButtonAdd_Click" />  
                </FooterTemplate>  
            </asp:TemplateField>  
            <asp:TemplateField>  
                <ItemTemplate>  
                    <asp:LinkButton ID="LinkButton1" runat="server"   
                                            onclick="LinkButton1_Click">Remove</asp:LinkButton>  
                </ItemTemplate>  
            </asp:TemplateField>  
        </Columns>  
    </asp:gridview>  

    </div>
    <p>
        &nbsp;</p>
    <asp:TextBox ID="lblMessage" runat="server"></asp:TextBox>
&nbsp;
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
        Text="BtnSave" />
    </form>
</body>
</html>




in cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Collections.Specialized;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;


namespace WebApplication11
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SetInitialRow();
            }
        }




        // private ArrayList GetDummyData()
        //{

        // ArrayList arr = new ArrayList();

        //arr.Add(new ListItem("Item1", "1"));
        //arr.Add(new ListItem("Item2", "2"));
        //arr.Add(new ListItem("Item3", "3"));
        //arr.Add(new ListItem("Item4", "4"));
        // arr.Add(new ListItem("Item5", "5"));

        //return arr;
        // }
        // private void FillDropDownList(DropDownList ddl)
        //{
        // ArrayList arr = GetDummyData();

        // foreach (ListItem item in arr)
        // {
        //  ddl.Items.Add(item);
        // }
        // }
        private void SetInitialRow()
        {

            DataTable dt = new DataTable();
            DataRow dr = null;

            dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
            dt.Columns.Add(new DataColumn("Column1", typeof(string)));//for DropDownList selected item   
            dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for DropDownList selected item  
            dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for TextBox value   
            dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for TextBox value   


            dr = dt.NewRow();
            dr["RowNumber"] = 1;
            // dr["Column3"] = 555;
            dr["Column3"] = string.Empty;
            dr["Column4"] = string.Empty;
            dt.Rows.Add(dr);

            //Store the DataTable in ViewState for future reference   
            ViewState["CurrentTable"] = dt;

            //Bind the Gridview   
            Gridview1.DataSource = dt;
            Gridview1.DataBind();

            //After binding the gridview, we can then extract and fill the DropDownList with Data   
            DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[1].FindControl("DropDownList3");
            DropDownList ddl2 = (DropDownList)Gridview1.Rows[0].Cells[2].FindControl("DropDownList4");
            //  FillDropDownList(ddl1);
            // FillDropDownList(ddl2);
        }
        private void AddNewRowToGrid()
        {

            if (ViewState["CurrentTable"] != null)
            {

                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;

                if (dtCurrentTable.Rows.Count > 0)
                {
                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;

                    //add new row to DataTable   
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    //Store the current data to ViewState for future reference   

                    ViewState["CurrentTable"] = dtCurrentTable;


                    for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
                    {



                        //extract the DropDownList Selected Items   

                        DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[1].FindControl("DropDownList3");
                        DropDownList ddl2 = (DropDownList)Gridview1.Rows[i].Cells[2].FindControl("DropDownList4");

                        // Update the DataRow with the DDL Selected Items   

                       dtCurrentTable.Rows[i]["Column1"] = ddl1.SelectedItem.Text;
                        dtCurrentTable.Rows[i]["Column2"] = ddl2.SelectedItem.Text;

                        //extract the TextBox values   



                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("TextBox1");
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("TextBox2");

                        dtCurrentTable.Rows[i]["Column3"] = box1.Text;
                        dtCurrentTable.Rows[i]["Column4"] = box2.Text;

                    }
                    //Rebind the Grid with the current data to reflect changes   
                    Gridview1.DataSource = dtCurrentTable;
                    Gridview1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");

            }
            //Set Previous Data on Postbacks   
            SetPreviousData();
        }
        private void SetPreviousData()
        {
            SqlConnection cnn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=medical_store_management2;Integrated Security=True");

            int rowIndex = 0;
            if (ViewState["CurrentTable"] != null)
            {

                DataTable dt = (DataTable)ViewState["CurrentTable"];
                if (dt.Rows.Count > 0)
                {

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {

                        //TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
                        // TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");

                        // DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
                        // DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");

                        DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList3");
                        DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList4");
                        TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");

                        TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");

                        //Fill the DropDownList with Data   
                        //  FillDropDownList(ddl1);
                        // FillDropDownList(ddl2);

                        if (i < dt.Rows.Count - 1)
                        {

                            String sql = ("select price from medicine where med_name='" + ddl1.Text + "'");
                            cnn.Open();
                            SqlCommand cmd = new SqlCommand(sql, cnn);
                            SqlDataReader dr;
                            dr = cmd.ExecuteReader();


                            //Set the Previous Selected Items on Each DropDownList  on Postbacks   
                            ddl1.ClearSelection();
                            ddl1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;

                            ddl2.ClearSelection();
                            ddl2.Items.FindByText(dt.Rows[i]["Column2"].ToString()).Selected = true;

                            //Assign the value from DataTable to the TextBox   
                            if (dr.Read())
                            {
                                box1.Text = dr.GetValue(0).ToString();
                            }
                            cnn.Close();
                            //box1.Text = dt.Rows[i]["Column3"].ToString();
                            box2.Text = dt.Rows[i]["Column4"].ToString();

                        }

                        rowIndex++;
                    }
                }
            }
        }
        protected void ButtonAdd_Click(object sender, EventArgs e)
        {
            AddNewRowToGrid();
        }
        protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataTable dt = (DataTable)ViewState["CurrentTable"];
                LinkButton lb = (LinkButton)e.Row.FindControl("LinkButton1");
                if (lb != null)
                {
                    if (dt.Rows.Count > 1)
                    {
                        if (e.Row.RowIndex == dt.Rows.Count - 1)
                        {
                            lb.Visible = false;
                        }
                    }
                    else
                    {
                        lb.Visible = false;
                    }
                }
            }
        }
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
            int rowID = gvRow.RowIndex;
            if (ViewState["CurrentTable"] != null)
            {

                DataTable dt = (DataTable)ViewState["CurrentTable"];
                if (dt.Rows.Count > 1)
                {
                    if (gvRow.RowIndex < dt.Rows.Count - 1)
                    {
                        //Remove the Selected Row data and reset row number  
                        dt.Rows.Remove(dt.Rows[rowID]);
                        ResetRowID(dt);
                    }
                }

                //Store the current data in ViewState for future reference  
                ViewState["CurrentTable"] = dt;

                //Re bind the GridView for the updated data  
                Gridview1.DataSource = dt;
                Gridview1.DataBind();
            }

            //Set Previous Data on Postbacks  
            SetPreviousData();
        }
        private void ResetRowID(DataTable dt)
        {
            int rowNumber = 1;
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    row[0] = rowNumber;
                    rowNumber++;
                }
            }
        }

        private void InsertRecords(StringCollection sc)
        {
            StringBuilder sb = new StringBuilder(string.Empty);
            string[] splitItems = null;
            const string sqlStatement = "INSERT INTO medsale1 (mname,qty,price,total) VALUES";
            foreach (string item in sc)
            {
                if (item.Contains(","))
                {
                    splitItems = item.Split(",".ToCharArray());
                    sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
                }
            }

            using (SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=medical_store_management2;Integrated Security=True"))
            {
                connection.Open();
                using (SqlCommand cmd = new SqlCommand(sb.ToString(), connection))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.ExecuteNonQuery();
                }
            }
            lblMessage.Text = "Records successfully saved!";
        }
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            int rowIndex = 0;
            StringCollection sc = new StringCollection();
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values  
                        DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList3");
                        DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList4");
                        TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
                        TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
                        //get the values from TextBox and DropDownList  
                        //then add it to the collections with a comma "," as the delimited values  
                        sc.Add(string.Format("{0},{1},{2},{3}", ddl1.SelectedItem.Text, ddl2.SelectedItem.Text, box1.Text, box2.Text));
                        //  sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, box2.Text, ddl1.SelectedItem.Text, ddl2.SelectedItem.Text));
                        rowIndex++;
                    }
                    //Call the method for executing inserts  
                    InsertRecords(sc);
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            int rowIndex = 0;
            StringCollection sc = new StringCollection();
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values  
                        DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList3");
                        DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList4");
                        TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
                        TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
                        // DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
                        // DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");

                        //get the values from TextBox and DropDownList  
                        //then add it to the collections with a comma "," as the delimited values  
                        sc.Add(string.Format("{0},{1},{2},{3}", ddl1.SelectedItem.Text, ddl2.SelectedItem.Text, box1.Text, box2.Text));
                        rowIndex++;
                    }
                    //Call the method for executing inserts  
                    InsertRecords(sc);
                }

            }
        }

    }
}

挑选
藏红花素
高露洁
挑选
1.
2.
3.
4.
去除

在cs中 使用制度; 使用System.Collections.Generic; 使用System.Linq; 使用System.Web; 使用System.Web.UI; 使用System.Web.UI.WebControl; 使用系统集合; 使用系统数据; 使用System.Collections.Specialized; 使用系统文本; 使用System.Data.SqlClient; 使用系统配置; 命名空间WebApplication11 { 公共部分类WebForm1:System.Web.UI.Page { 受保护的无效页面加载(对象发送方、事件参数e) { 如果(!Page.IsPostBack) { SetInitialRow(); } } //私有ArrayList GetDummyData() //{ //ArrayList arr=新的ArrayList(); //arr.Add(新列表项目(“项目1”、“1”)); //arr.Add(新列表项(“第2项”、“第2项”); //arr.Add(新列表项(“第3项”、“第3项”); //arr.Add(新列表项(“第4项”、“第4项”); //arr.Add(新列表项(“第5项”、“第5项”); //返回arr; // } //私有void FillDropDownList(DropDownList ddl) //{ //ArrayList arr=GetDummyData(); //foreach(arr中的列表项) // { //ddl.Items.Add(项目); // } // } 私有void SetInitialRow() { DataTable dt=新的DataTable(); 数据行dr=null; 添加(新的数据列(“行数”,typeof(字符串)); dt.Columns.Add(新数据列(“Column1”,typeof(string));//用于DropDownList所选项目 dt.Columns.Add(新数据列(“Column2”,typeof(string));//用于DropDownList所选项目 dt.Columns.Add(新数据列(“Column3”,typeof(string));//用于文本框值 dt.Columns.Add(新数据列(“Column4”,typeof(string));//用于文本框值 dr=dt.NewRow(); dr[“行数”]=1; //dr[“Column3”]=555; dr[“Column3”]=string.Empty; dr[“Column4”]=string.Empty; dt.Rows.Add(dr); //将DataTable存储在ViewState中以供将来参考 视图状态[“当前表”]=dt; //绑定Gridview Gridview1.DataSource=dt; Gridview1.DataBind(); //绑定gridview后,我们可以提取数据并用数据填充DropDownList DropDownList ddl1=(DropDownList)Gridview1.Rows[0]。单元格[1]。FindControl(“DropDownList 3”); DropDownList ddl2=(DropDownList)Gridview1.Rows[0]。单元格[2]。FindControl(“DropDownList 4”); //FillDropDownList(ddl1); //FillDropDownList(ddl2); } 私有void AddNewRowToGrid() { 如果(ViewState[“CurrentTable”]!=null) { DataTable dtCurrentTable=(DataTable)视图状态[“CurrentTable”]; DataRow drCurrentRow=null; 如果(dtCurrentTable.Rows.Count>0) { drCurrentRow=dtCurrentTable.NewRow(); drCurrentRow[“RowNumber”]=dtCurrentTable.Rows.Count+1; //向DataTable添加新行 dtCurrentTable.Rows.Add(drCurrentRow); //将当前数据存储到ViewState以供将来参考 ViewState[“CurrentTable”]=dtCurrentTable; 对于(int i=0;iOnSelectedIndexChanged="DropDownList3_SelectedIndexChanged" OnSelectedIndexChanged="DropDownList4_SelectedIndexChanged"
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList medicineName = (DropDownList)sender;
    if (medicineName.SelectedValue != "-1") // if medicine name is selected
    {
        GridViewRow row = (GridViewRow)medicineName.Parent.Parent; // find row 
        int quantity = Convert.ToInt32(((DropDownList)row.FindControl("DropDownList4")).SelectedValue); // find Quantity 
        if (quantity != -1) // if quanity is selected
        {
            int price = 1; // TODO: here you take the prize from the database by medicine name
            price = price * quantity;
            TextBox txtPrice = (TextBox)row.FindControl("TextBox1"); // find price textbox for this row
            txtPrice.Text = Convert.ToString(price); // assign price value to this textbox
        }
    }
}