点餐系统:双击DataGridView无法获取单品原价(值恒为0)求助
Hey there! Let's break down why you're consistently getting a 0 value for the dish's original price when double-clicking rows in your DataGridView, and fix it step by step.
Common Causes & Fixes
1. You're Not Targeting the Correct Column (or Using Wrong Column Name/Index)
This is the most likely culprit. Let's make sure you're pulling the price from the right DataGridView cell.
First, confirm:
- Your DataGridView is bound to a data source (like a DataTable) that includes the original price field.
- The column name (or index) you're using matches exactly what's in your data source.
Here's a corrected version of your double-click event handler, with safety checks:
public void dataGridView1_DoubleClick(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count > 0) { DataGridViewRow selectedRow = dataGridView1.SelectedRows[0]; // Get dish name (adjust column name to match your actual column) string dishName = selectedRow.Cells["DishName"].Value.ToString(); // Get original price with null/DBNull check decimal originalPrice = 0; var priceCellValue = selectedRow.Cells["OriginalPrice"].Value; // Use your actual price column name if (priceCellValue != DBNull.Value && priceCellValue != null) { originalPrice = Convert.ToDecimal(priceCellValue); } else { // Optional: Handle cases where price is missing (show error, etc.) MessageBox.Show("Warning: No price found for this dish!"); return; } // Pass the original price to your quantity input form QuantityInputForm quantityForm = new QuantityInputForm(originalPrice); if (quantityForm.ShowDialog() == DialogResult.OK) { int quantity = quantityForm.SelectedQuantity; decimal totalPrice = originalPrice * quantity; // Add to ListView ListViewItem orderItem = new ListViewItem(dishName); orderItem.SubItems.Add(quantity.ToString()); orderItem.SubItems.Add(totalPrice.ToString("C")); // Format as currency listView1.Items.Add(orderItem); } } }
2. Your Data Source Isn't Loading the Price Correctly
If the cell value is genuinely 0, check your database query:
- Make sure your
SELECTstatement includes the original price column (e.g.,SELECT DishID, DishName, OriginalPrice FROM Menu). - Verify the database table has valid non-zero values for the price field for your dishes.
3. You're Using the Wrong Data Type Conversion
If your price is stored as a decimal or float in the database, avoid converting it to an int first—this will truncate decimals to 0 if the value is less than 1, or cause unexpected results. Always use decimal for currency values to maintain precision.
Quick Debug Tip
Add a breakpoint on the line where you retrieve the price value. Hover over priceCellValue to see what it actually contains. If it's DBNull or 0, you'll know whether the issue is in the data source or your cell selection logic.
内容的提问来源于stack exchange,提问作者Justine Cortez

