'对象'不包含'行'的定义没有延伸方法'行'接受类型'对象'的第一个参数。可以找到

时间:2014-10-08 14:01:18

标签: c# asp.net database

  

'Object'不包含'Rows'的定义,也没有扩展名   方法'Rows'接受'object'类型的第一个参数可能是   发现您是否缺少using指令或程序集引用?

代码如下:

public partial class Default3 : System.Web.UI.Page
{
    static SqlConnection con = new SqlConnection(@"connectionString");
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!this.IsPostBack)
        {
            ddlImg.DataSource = GetData("SELECT EmpID, EmpName FROM Tbl_Emp");
            ddlImg.DataTextField = "EmpName";
            ddlImg.DataValueField = "EmpID";
            ddlImg.DataBind();
        }

    }

    private object GetData(string query)
    {
        DataTable dt = new DataTable();
        string constr = ConfigurationManager.ConnectionStrings["tbFiles2ConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                }
            }
            return dt;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand();
        con.Open();
        cmd.Connection = con;
        cmd.CommandText = ("INSERT INTO Tbl_Emp(EmpID, EmpName, EmpPic ) VALUES('"+TextBox1.Text+"','"+TextBox2.Text+"','" + FileUpload1 + "')");
        cmd.ExecuteNonQuery();
        con.Close();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string id = ddlImg.SelectedItem.Value;
        Image1.Visible = id != "0";
        if (id != "0")
        {
            byte[] bytes = (byte[])GetData("SELECT Data FROM Tbl_Emp WHERE Emp_ID =" + id).Rows[0]["Data"]; // Error popup here
            string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
            Image1.ImageUrl = "data:image/png;base64," + base64String;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

问题是GetData返回没有object属性的Rows。因此,您在以下位置收到编译器错误:

...GetData("SELECT Data FROM Tbl_Emp WHERE Emp_ID =" + id).Rows[0]...

返回DataTable代替:

private DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["tbFiles2ConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }
    }
    return dt;
}

请注意,

答案 1 :(得分:1)

getdata()功能签名更改为

private DataTable GetData(string query){

}