1

我正在尝试使用 datareader 从数据库中的特定表中显示特定值。正如您从我的 sql 查询中看到的那样,我使用来自 3 个单独的表和 memberreportid 的数据,并且用户名具有 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();

    }
4

2 回答 2

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);
于 2013-05-27T08:17:41.427 回答
0

Try this

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 example

于 2013-05-28T06:02:42.163 回答