通过使用从另一种形式传递给它的参数来提取一种形式中的细节

本文关键字:提取 细节 参数 一种 另一种 | 更新日期: 2023-09-27 18:09:11

我用c#创建了两个窗体。表单链接到数据库。

在表单1中,我从"ListView"表中显示客户列表,并从中选择一个。所选人员的Id通过构造函数传递给第二个表单。

在表单2中,我试图提取具有传递Id的人的详细信息。

我正在尝试通过使用Execute Reader类型的变量将详细信息("姓名,电话号码,地址")读取到表单2的文本框中。

但是文本框没有显示表中所需的数据。在调试中,控件似乎没有进入While循环。

public partial class Form2 : Form
{
    int id;
    Form2 mainform;
    public Form1 mainForm = null;
    public Form2(Form callingForm, string x)
    {
        mainForm = callingForm as Form1;
        id = int.Parse(x);//x gets its value from form 1
        MessageBox.Show(id.ToString());
        InitializeComponent();
    }
    private void Form2_Load(object sender, EventArgs e)
    {
        try
        {
            SqlConnection cn2 = new SqlConnection();
            cn2.ConnectionString = "Data Source= xyz;InitialCatalog=db1;User = xyz1;Password = one";
            cn2.Open();
            string str2 = "select * from CustomerProfile as p  inner join CustomerTable as c on c.ID = p.ID where ID = " + id;
            SqlCommand myCommand1 = new SqlCommand(str2, cn2);
            SqlDataReader Myread1;
            Myread1 = myCommand1.ExecuteReader();
            MessageBox.Show(Myread1[0].ToString());
            while (Myread1.Read())
            {//The data is not getting read here    
                textBox1.Text = Myread1[0].ToString();
                textBox2.Text = Myread1[1].ToString();
                textBox3.Text = Myread1[2].ToString();
            }
        }
        //Myread1.Close();
        catch (Exception err)
        { //rather its displaying these messages.
            textBox1.Text = "Error reading names";
            textBox2.Text = "hi";
        }
    }
}

什么可能是我的数据没有显示的根本原因,而是来自try/catch处理程序的Error reading names ?

通过使用从另一种形式传递给它的参数来提取一种形式中的细节

catch块中的代码被执行,因此在某处抛出异常。其中一个肯定会出现在以下行:

MessageBox.Show(Myread1[0].ToString());
因为你试图在读取数据之前访问它(Read())。

您的sql语句失败,因为它不知道id列属于哪个表,您在where子句中使用

如果你将参数从你的代码传递给sqlcommand,那么使用SqlParameters。

string str2 = @"select * 
                from CustomerProfile as p  
                inner join CustomerTable as c on c.ID = p.ID
                where c.ID = @pid"; // notice the c.id here and the parameter
var parmId = new SqlParameter("pid", id);
SqlCommand myCommand1 = new SqlCommand(str2, cn2);
myCommand1.Parameters.Add(parmId);

我在上面的代码中为你修复了这两个问题。

你必须在访问数据之前调用Read,所以你的消息框在你进入while循环之前必须离开,这在SqlDataReader类中解释。

 // you can't access the reader yet..  
 // MessageBox.Show(Myread1[0].ToString());

如果出现异常,你最好显示它们(或记录它们):

catch (Exception err)
{ //rather its displaying these messages.
     Debug.WriteLine(err.Message);
     textBox1.Text = "Error reading names";
     textBox2.Text = err.Message;
}