我正在创建账单表单。在其中,我在gridview中添加了文本框和下拉列表。现在在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>
</p>
<asp:TextBox ID="lblMessage" runat="server"></asp:TextBox>
<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);
}
}
}
}
}
您可以通过检测用户何时选择medicine name
或quantity
来实现这一点。为了做到这一点,只需为您的两个DropDownLists
:添加OnSelectedIndexChanged
OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged"
OnSelectedIndexChanged="DropDownList4_SelectedIndexChanged"
每次更改项目的选择时,此事件都会激发。您还需要为DropDownLists
和true
设置AutoPostBack
属性,否则事件不会激发。
现在你的代码可以如下所示:
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
}
}
}
每次用户在medicine name dropdownlist
中选择项目时,方法都会检查是否选择了数量,如果是,则从数据库中获取价格,乘以quantity
并将该值分配给textbox
。当然,在上面的例子中,当你应该从数据库中获取价格时,我没有实现这个部分。与实现quanity dropdownlist
事件的方式相同。