在我的Windows窗体应用程序中,DataGridView
从文本框的TextChanged_Event
更新(条形码读取功能)。每个新行都具有产品名称,数量,单价和总金额之类的值。 产品名称和单价值来自数据库,而我为数量设置了默认值1。 总金额的值是数量和单价的乘积。
到目前为止一切正常,我可以为每个商品的销售数量使用默认的1值。但是,如果我要出售一件以上的商品,则需要用自定义值替换此默认数量值。
为简化此过程,我使用了带有单个文本框和按钮的子表单,该按钮允许我的用户为“数量”列输入自定义值,该值应替换默认的1值。数量列。
我没有运气就尝试了不同的方法。因为我正在“销售”过程的那一部分显示子窗体,在该部分中应用程序必须在DataGridView中查找重复的产品。如果DataGridView中已经存在某个项目,则应用程序会要求再次添加该项目,并且当用户单击“是”按钮时,将显示子窗体。
因此,这使我的逻辑变得毫无意义,因为在显示并处理了子窗体上的自定义“数量”值文本框后,我无法访问父窗体上的变量以用此自定义数量替换其默认值1。
我的代码工作正常,但是我需要在逻辑上做一些改进,以便可以轻松地用子窗体中的自定义值替换默认的“数量”值。
这是我的代码:
public void FillCurrentSoldItemGrid(string barCode)
{
string columnList = "ProductName, UnitPrice";
DataRow dr = NewSale.SelectByItemCode(columnList, barCode);
if (dr == null)
{
//show error message
return;
}
// check duplicate value in DataGridView
string productName = dr[0].ToString();
if (dgvSoldItems.RowCount > 0)
{
foreach (DataGridViewRow dgvRow in dgvSoldItems.Rows)
{
if (dgvRow.Cells[0].Value.ToString().CompareTo(productName) == 0)
{
if (DataAccess.AskUser("This item is already present in the grid?", "Confirm Item Quantity Update") == true)
{
//my child form code
using (var customSaleQuantity = new frmCustomSaleQuantity())
{
var result = customSaleQuantity.ShowDialog();
if (result == DialogResult.OK)
{
//need to assign this value of the customQuantity string to int quantity which is holding a default 1 value)
string customQuantity = customSaleQuantity.GetCustomQuantity;
}
}
}
}
}
}
//value of string customQuantity to be assigned to int quantity.
int quantity = 1;
int unitPrice = Convert.ToInt32(dr[1]);
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dgvAllSoldItems);
row.Cells[0].Value = productName;
row.Cells[1].Value = quantity;
row.Cells[2].Value = unitPrice;
row.Cells[3].Value = (quantity * unitPrice);
dgvAllSoldItems.Rows.Add(row);
}
这是我的子表单中的代码:
public string GetCustomQuantity
{
get;
set;
}
private void btnProceedWithNewItemQuantity_Click(object sender, EventArgs e)
{
this.GetCustomQuantity = txtChooseSaleQuantity.Text.Trim();
this.Close();
}
我是C#的新手,我不知道如何在检测到重复项时用自定义值替换默认的数量1值。这是非常重要的任务,我的截止日期快要结束了。
任何帮助将不胜感激。
答案 0 :(得分:0)
有很多方法可以改善逻辑;但是,一种方法是应用面向对象编程(OOP)的概念。 定义一个静态类来保存全局变量,字段和函数。 用户以子窗体形式输入数据后,将该信息传递给静态类getter / setter方法。另外,在您的静态类中,您可以定义一个公共函数来处理数据。 不要忘记刷新GridView来查看更新的信息。 我建议使用静态类的主要原因是,该类可以在应用程序中的任何位置调用公共属性,方法,而无需创建类对象的实例。
static class Globals
{
// global int
public static int counter;
// global function
public static string HelloWorld()
{
return "Hello World";
}
}
Globals.counter = 10;
int localcounter = Globals.counter;
string somestring = Globals.HelloWorld();
Globals.counter2 = 30;
int localcounter2 = Globals.counter2;