0

我动态创建我需要的控件这
是代码 

public void cmdButton1_OnClick(object sender, EventArgs e)
{

        Label myLabel = new Label();
        myLabel.ID = "lblNameL" + i.ToString();
        myLabel.Text = "Трите имена на латиница ";
        TextBox myTextBox1 = new TextBox();
        myTextBox1.ID = "txtNameL" + i.ToString();
        Page.FindControl("form1").Controls.Add(myLabel);
        Page.FindControl("form1").Controls.Add(myTextBox1);

        Label mylabel2 = new Label();
        mylabel2.ID = "lblNameK" + i.ToString();
        mylabel2.Text = "Трите имена на кирилица";
        TextBox myTextBox2 = new TextBox();
        myTextBox2.ID = "txtNameK" + i.ToString();
        Page.FindControl("form1").Controls.Add(mylabel2);
        Page.FindControl("form1").Controls.Add(myTextBox2);
}

在这里我尝试执行 sql 查询,以便我可以将写入文本框的内容txbNameK插入到表Tourist中,异常在行中cmd.Parameters.add

public void cmdInsert_OnClick(object sender, EventArgs e)
{

        TextBox tx888 = (TextBox)FindControl("txtNameK" + i.ToString());
        TextBox tx99 = (TextBox)FindControl("txtNameL" + i.ToString());

        string insertSQL = "INSERT INTO Tourist ( Name_kir, Name_lat) VALUES (@Name_kir, @Name_lat, )";

        string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=Pubs;Integrated Security=SSPI";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(insertSQL, con);
        cmd.Parameters.AddWithValue("@Name_kir",tx888);
        cmd.Parameters.AddWithValue("@Name_lat", tx99);

        int added = 0;
        try
        {
            con.Open();
            added = cmd.ExecuteNonQuery();
            lblResult.Text = added.ToString() + "records added";

        }
        catch (Exception ex)
        {
            lblResult.Text = ex.Message;
        }
        finally
        {
            con.Close();

        }
    }
}
4

2 回答 2

1

两件事情:

文本框 tx888 = (TextBox)FindControl("txtNameK" + i.ToString());
文本框 tx99 = (TextBox)FindControl("txtNameL" + i.ToString());
如果(tx888 == 空)
    返回;
如果(tx99 == 空)
    返回;

上面将检查您的 texbox 是否为 null 另一件事是:

cmd.Parameters.AddWithValue("@Name_kir",tx888.Text);
cmd.Parameters.AddWithValue("@Name_lat", tx99.Text);
于 2012-11-21T13:15:11.670 回答
0

Object reference exception always occurs whenever null object is trying to access any value. eg..

Code below will work fine.

Exception ex = new Exception()
Textbox1.Text = ex.Message;

Code below will throw an exception

Exception ex= null;    //one and the same thing

Textbox1.Text = ex.Message;     //Object reference not set....exception will be raised since ex is null

This is what is happening in your code. Try to place a breakpoint and debug it. For best practice always check for an object for null as suggested by Prashant.

于 2012-11-21T13:23:22.187 回答