[英]C# how to copy datagridview's currentrow to single datarow?
[英]How to update the target cell of a CurrentRow in DataGridView in C#?
在我的Windows窗体应用程序中, DataGridView
是从文本框的TextChanged_Event
(条形码读取功能)更新的。 每个新行都具有诸如“ 产品名称”,“数量”,“单价”和“ 总金额”之类的值 。 产品名称和单价值来自数据库的,而我已经设置的1对数量的默认值。 总金额的值是数量与单价的乘积。
到目前为止,一切正常,我可以使用默认的1值表示每个项目的销售数量 。 但是,如果我要出售一件以上的商品,则需要用自定义值替换此默认数量值。
为了简化此过程,我使用了一个带有单个文本框和一个按钮的子窗体 ,该按钮将允许我的用户为“数量”列放置一个自定义值,该值应替换“数量”列的默认值1。
我没有运气就尝试过其他方法。 因为我在Sale流程的那一部分显示子窗体,因此应用程序必须在DataGridView中查找重复的产品 。 如果DataGridView中已经存在一个项目,则应用程序会要求再次添加该项目,并且当用户单击“是”按钮时,将显示子窗体 。
因此,这使我的逻辑变得毫无意义,因为在显示并使用子窗体上的自定义“数量”值文本框后,我无法访问父窗体上的变量以用此自定义数量替换其默认值1。
我的代码工作正常,但是我仅需要逻辑上的一些改进,以便可以轻松地将默认的Value值替换为Child Form中的自定义值。
这是我的代码:
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值。 这是非常重要的任务,我的截止日期快要结束了。
任何帮助将不胜感激。
有很多方法可以改善逻辑; 但是,一种方法是应用面向对象编程(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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.