在表中的标签上显示数据库值

时间:2013-05-27 08:13:30

标签: c# asp.net sql

我正在尝试使用datareader来显示数据库中特定表的特定值。从我的sql查询中可以看出,我使用了来自3个独立表的数据,memberreportid和username都有PK和FK r / s。 不幸的是,我无法展示我想要的价值,如下所述。

这是我收到的错误

用户代码未处理IndexOutOfRangeException

我逐行评论显示值代码,实际上所有收到上述错误

这是我的代码。

protected void DDLCase_SelectedIndexChanged(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = project; Integrated Security = SSPI");
        con.Open();
        SqlCommand cm = new SqlCommand("Select * from MemberReport mr, PoliceReport pr, LoginRegisterOthers lro where pr.memberreportid = '" + DDLCase.SelectedItem.Text + "' and mr.memberreportid=pr.memberreportid and lro.username=mr.username and caseprogress='settled'", con);
        SqlDataReader dr;
        dr = cm.ExecuteReader();
        if (dr.Read())
        {
            lblFullName.Text = dr["lro.fullname"].ToString();
            lblContact.Text = dr["lro.contact"].ToString();
            lblTOC.Text = dr["mr.typeofcrime"].ToString();
            lblLocation.Text = dr["mr.location"].ToString();
            lblCRDT.Text = dr["mr.CRdatetime"].ToString();
            lblPicture.Text = dr["picture"].ToString();
            lblAssign.Text = dr["pr.policeid"].ToString();
            lblPRDT.Text = dr["pr.PRdatetime"].ToString();
            lblCR.Text = dr["mr.citizenreport"].ToString();
            lblPR.Text = dr["pr.policereport"].ToString();
        }

        con.Close();

    }

2 个答案:

答案 0 :(得分:4)

您正在使用“*”选择所有行,但之后您尝试使用表别名访问它们。无论哪种方式都可以更改您的查询:

Select mr.location, mr.typeofcrime ... etc from MemberReport mr, PoliceReport pr, LoginRegisterOthers lro where pr.memberreportid =

或在没有别名的datareader中访问它们:

lblFullName.Text = dr["fullname"].ToString();

我也强烈建议使用参数!

SqlCommand cm = new SqlCommand("Select mr.location, mr.typeofcrime ... etc from MemberReport mr, PoliceReport pr, LoginRegisterOthers lro where pr.memberreportid = @id and mr.memberreportid=pr.memberreportid and lro.username=mr.username and caseprogress='settled'");
cm.Parameters.AddWithValue("@id", DDLCase.SelectedItem.Text);

答案 1 :(得分:0)

试试这个

SqlDataAdapter adapter = new SqlDataAdapter("Select * from MemberReport mr, PoliceReport pr, LoginRegisterOthers lro where pr.memberreportid = '" + DDLCase.SelectedItem.Text + "' and mr.memberreportid=pr.memberreportid and lro.username=mr.username and caseprogress='settled'", con);

    DataTable tbl = new DataTable();

adapter.Fill(tbl);

foreach(DataRow row in tbl.Rows)
{
 //use row data here as row["column_name"].ToString()
}

SqlDataAdapter示例