我有一个带有文本框的表单,可以将数据插入到datagridview中。当我输入数据时,它成功地将其输入到datagridview中,这很好。但是,如果我在不输入数据的情况下关闭表单,它会在数据网格视图中插入一个空行,然后在其下面开始一个新行,准备接收更多数据。如何防止它插入空白行?
public partial class newquoteForm : Form
{
public newquoteForm()
{
InitializeComponent();
}
DataTable dt = new DataTable();
public void newquoteForm_Load(object sender, EventArgs e)
{
DataRow dr;
dt.Columns.Add("Item Name");
dt.Columns.Add("Item Description");
dt.Columns.Add("Retail Price");
dt.Columns.Add("Cost Price");
dt.Columns.Add("In Stock");
dt.Columns.Add("On Jobs");
dr = dt.NewRow();
dataGridView1.DataSource = dt;
}
public void addBTN_Click(object sender, EventArgs e)
{
additemForm additemForm = new additemForm();
additemForm.ShowDialog();
dt.Rows.Add(additemForm.strItem, additemForm.strDesc, additemForm.strRetail); // some methods are missing, Don't worry about it.
dataGridView1.DataSource = dt;
}
}
答案 0 :(得分:1)
看起来您的AddItemForm
有一些属性可用于在addBTN_Click
执行时创建新行。您永远不会检查AddItemForm
是否正确初始化了这些属性。您只需添加这些属性的值,即使这些值为空也是如此。我将AddItemForm
添加一个属性,如IsValid
,只有在其他属性正确初始化时才会生效。然后在创建新行之前检查它。
在AddItemForm中:
public bool IsValid {
get {
return !string.IsNullOrEmpty(txtStrItem.Text) &&
!string.isNullOrEmpty(your other textboxes)...;
// I'm just guessing here what controls your form has. you should see the point though
}
}
然后当你创建新行时:
using (var addItemForm = new AddItemForm()) {
if (addItemForm.ShowDialog() == DialogResult.OK) {
if (addItemForm.IsValid) {
dt.Rows.Add(additemForm.strItem, additemForm.strDesc, additemForm.strRetail);
}
}
}
答案 1 :(得分:0)
假设我创建了一个带有三个文本框的additemForm表单,然后在表单的关闭时设置strItem,strDesc和strRetail属性。我还将设置Dialog结果:
void additemForm_Closing(object sender, CancelEventArgs e)
{
strItem = this.textBox1.Text;
strDesc = this.textBox2.Text;
strRetail = this.textBox3.Text;
//You can check anything here
if (string.IsNullOrEmpty(strItem))
{
this.DialogResult = DialogResult.Cancel;
}
else
{
this.DialogResult = DialogResult.OK;
}
}
现在在主窗体中,您可以检查对话框结果,然后对其进行操作:
additemForm additemForm = new additemForm();
DialogResult dialogResult = additemForm.ShowDialog();
if (dialogResult == DialogResult.Cancel)
{
return;
}
dt.Rows.Add(additemForm.strItem, additemForm.strDesc, additemForm.strRetail); // some methods are missing, Don't worry about it.
dataGridView1.DataSource = dt;