在datagridview c#中调用void函数
本文关键字:void 函数 调用 datagridview | 更新日期: 2023-09-27 18:23:56
如何在该数据gridview
中调用我的函数?我想在高亮显示的datagridview
:中显示这两者的总和
foreach (DataRow row in dt.Rows) {
datagridview_information.Rows.Add();
datagridview_information.Rows[counterSelected].Cells[0].Value = row["BrandName"].ToString();
datagridview_information.Rows[counterSelected].Cells[1].Value = row["GenericName"].ToString();
datagridview_information.Rows[counterSelected].Cells[2].Value = row["PresDayOfIntake"].ToString();
datagridview_information.Rows[counterSelected].Cells[3].Value = row["Status"].ToString();
datagridview_information.Rows[counterSelected].Cells[4].Value = "5";
datagridview_information.Rows[counterSelected].Cells[5].Value = medicineLeft();
datagridview_information.Rows[counterSelected].Cells[7].Value = row["ContainerNumber"].ToString();
datagridview_information.Rows[counterSelected].Cells[8].Value = row["Status"].ToString(); ;
counterSelected++;
}
}
}
public int medicineLeft()
{
for (int i = 0; i < datagridview_schedule.Rows.Count; ++i)
{
medleft += Convert.ToInt32(datagridview_information.Rows[i].Cells[8]) - Convert.ToInt32(datagridview_medicine.Rows[i].Cells[4]);
datagridview_information.Rows[i].Cells[5].Value = Convert.ToString(medleft);
}
return medicineLeft();
}
你必须在这里给出更多的代码,我完全不知道你想做什么。medleft在其他地方声明了吗?
您的medicineLeft()方法正在返回自身,这意味着它将作为一个无限循环运行,并且可能会在以下行引发StackOverflow异常:
datagridview_information.Rows[counterSelected].Cells[5].Value = medicineLeft();
您的medicineLeft方法需要返回一个整数-它是否意味着返回medleft?如果是这样,将其更改为return medleft;
应该可以解决此问题。
一个简单的解决方案是更改DataGridView
的填充方式。如果我这样做,我会做以下事情:
-
创建一个类对象来存储网格中所需的数据:
public class Medicine { public string BrandName { get; set; } public string GenericName { get; set; } <... add other properties ...> }
-
实例化要绑定到
DataGridView
的Medicine
对象的集合。public List<Medicine> GetMedicine(DataRowCollection rows) { List<Medicine> medicines = new List<Medicine>(); foreach (DataRow row in rows) { Medicine medicine = new Medicine(); medicine.BrandName = row["BrandName"] == null ? string.Empty : row["BrandName"].ToString(); medicine.GenericName = row["GenericName"] == null ? string.Empty : row["GenericName"].ToString(); //more rows here to populate Medicine object //include the call to whatever methods are needed to populate the object medicines.Add(medicine); } return medicines; }
-
将集合绑定到
DataGridView
datagridview_information.DataSource = GetMedicines(dt.Rows);
我发现在表单上创建DataGridView
控件、在设计器中设置列以及在代码中将AutoGenerateColumns
属性设置为false
都很容易,这样网格就可以随心所欲地显示了。这取决于你想如何处理。