从组件到类调用组件并将数据保存回表

时间:2014-03-18 13:12:41

标签: ado.net method-call local-database

我正在研究ado.net项目,我以前有代码的单独类, 现在我想了解更多关于本地数据库的信息,但是当我试图调用包含SQL命令的类时,我就是库存了 看看我的代码,我评论了我的库存

    namespace Maintenance
    {
        public partial class registerReports : Form
        {
            private void btnSave_Click(object sender, EventArgs e)
            {
                //the code works if it exists here
                /**
                    conn.Open();
                    com.Parameters.AddWithValue("@reportID",
                    tbReportIDox.Text);
                    com.ExecuteNonQuery();
                    conn.Close();
                **/
            }
        }
    }

    class reportTableSQL 
    {
        public void reportTable()
        {
            string connectionString = connectionString = "Data Source=
            ..//..//maintenanceDB.sdf";
            SqlCeConnection conn = new SqlCeConnection(connectionString);

            using (SqlCeCommand com = new SqlCeCommand("INSERT INTO
            ReportForm VALUES(@reportID)", conn))
            {
                // if i call this method from class registerReports : Form
                // it doesn't recognise tbReportIDox.Text as
                //it isn't exist in this class

                /**
                    conn.Open();
                    com.Parameters.AddWithValue("@reportID",
                    tbReportIDox.Text);
                    com.ExecuteNonQuery();
                    conn.Close();
                **/
            }
        }
    }

谢谢

1 个答案:

答案 0 :(得分:0)

您可以做的是将tbReportIDox.Text作为参数拉到方法,即

public void reportTable(string reportName)
{   
    ...
    com.Parameters.AddWithValue("@reportID",    reportName);
    ...
}

然后点击按钮

private void btnSave_Click(object sender, EventArgs e)
{
        // resolve instance of reportTableSQL class
        // for example through: new reportTableSQL();
        var reportGenerator = new reportTableSQL();
        reportGenerator.reportTable(tbReportIDox.Text);
}