OleDB Parameters

戏子无情 提交于 2020-01-11 11:51:31

问题


I have this access db that I have a ddl for the state name and a ddl for the year. I have a gridview that I'd like to pass the value of the state drop down list into where clause. Obviously if I could use sql with the named parameters I would but this is what I'm stuck with and not sure exactly how to format it correctly.

the drop down list is name ddlStates. In the parameters I've tried

mycommand.Parameters.Add("@ddlStates")

here is the data set

        public DataSet GetData()
    {
        DataSet ds;
        using (OleDbConnection myConnString = new OleDbConnection())
        {
            myConnString.ConnectionString = connString;
            using (OleDbCommand myCommand = new OleDbCommand())
            {
                myCommand.CommandText = "select * from tblTest where location = ?";
                myCommand.Parameters.Add();
                myCommand.Connection = myConnString;



                using (OleDbDataAdapter da = new OleDbDataAdapter())
                {
                    da.SelectCommand = myCommand;
                    ds = new DataSet();
                    da.Fill(ds, "Grades");
                }
            }
            return ds;
        }
    }//ends get data dataset

回答1:


1.you need to open your connection

2.you can add the parameter as follows

public DataSet GetData()
{
    DataSet ds;
    using (OleDbConnection conn = new OleDbConnection(connString))
    {
        string query= "select * from tblTest where location = ?";            
        using (OleDbCommand myCommand = new OleDbCommand(query, conn))
        {

            myCommand.Parameters.AddWithValue("@ddlStates", <your value>);
            conn.Open();

            using (OleDbDataAdapter da = new OleDbDataAdapter(myCommand, conn))
            {
                ds = new DataSet();
                da.Fill(ds, "Grades");
                return ds;
            }
        }

    }
}



回答2:


myCommand.Parameters.AddWithKey("location", this.ddlStates.SelectedValue);

That assumes that the data type of the location column is textual. If it's numeric or something else then convert the SelectedValue to the appropriate data type first.



来源:https://stackoverflow.com/questions/21924636/oledb-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!