当我选择项目时,我使用组合框来显示项目,它在下面的文本框中显示该项目的ID,我已经在所选的更改索引事件中编写了代码,当我执行表单并关闭时表单没有在表单中做任何事情它显示我对象引用未设置为我的字符串查询中的对象的实例 我的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace TinyErp
{
public partial class frmaddprod : Form
{
public frmaddprod()
{
InitializeComponent();
}
private void productsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.productsBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.orderMachineDataSet);
}
SqlConnection conn = new SqlConnection(Properties.Settings.Default.OrderMachineConnectionString);
string strgetsupp;
private void frmaddprod_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'orderMachineDataSet.Suppliers' table. You can move, or remove it, as needed.
this.suppliersTableAdapter.Fill(this.orderMachineDataSet.Suppliers);
// TODO: This line of code loads data into the 'orderMachineDataSet.Products' table. You can move, or remove it, as needed.
this.productsTableAdapter.Fill(this.orderMachineDataSet.Products);
//string strgetsupp = "select supplier_id from Suppliers where supplier_company='" + ((DataRowView)comboBox1.SelectedItem).Row["supplier_company"].ToString() + "'";
//conn.Open();
//SqlCommand cmd = new SqlCommand(strgetsupp, conn);
//SqlDataReader read;
//read = cmd.ExecuteReader();
//read.Read();
//int sid = int.Parse(read["supplier_id"].ToString());
//read.Close();
//conn.Close();
//supplier_idTextBox.Text = sid.ToString();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
strgetsupp = "select supplier_id from Suppliers where supplier_company='" + ((DataRowView)comboBox1.SelectedItem).Row["supplier_company"].ToString() + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(strgetsupp, conn);
SqlDataReader read;
read = cmd.ExecuteReader();
read.Read();
int sid = int.Parse(read["supplier_id"].ToString());
supplier_idTextBox.Text = sid.ToString();
read.Close();
conn.Close();
}
private void productsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void frmaddprod_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
}
}
答案 0 :(得分:1)
在执行任何其他操作之前检查comboBox1.SelectedItem是否为空
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedItem==null)
return;
strgetsupp = "select supplier_id from Suppliers where supplier_company='" + ((DataRowView)comboBox1.SelectedItem).Row["supplier_company"].ToString() + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(strgetsupp, conn);
SqlDataReader read;
read = cmd.ExecuteReader();
read.Read();
int sid = int.Parse(read["supplier_id"].ToString());
supplier_idTextBox.Text = sid.ToString();
read.Close();
conn.Close();
}