索引超出范围。无法将 selectedIndexChanged 作为查询的索引

Index out of range. Can't get selectedIndexChanged as index for query

我得到一个 'index out of range error' 但是不知道为什么,

我有 gridview 主控件,我正在使用 SelectedIndexChanged 在详细信息视图中显示有关所选行的更多信息,但是当我尝试指向查询中的所选行时,它给出了索引超出范围错误。

我正在使用 ADO.NET 实体模型,并希望使用另一个名为 EventLog 的数据库 table 检索有关所选 gridview 行的数据,并用它填充详细信息视图。

Error Message (Line 50)

Line 50: description = Tquery[IntEid].EventLogs.FirstOrDefault().EventDesc.ToString();

Line 51: resultCode = Convert.ToInt32(Tquery[IntEid].EventLogs.FirstOrDefault().ResultCode);

这是我的 SelectedIndexChanged 代码:

<!-- language: lang-c# -->
string description;
int resultCode;
int TaskInstanceID;
string Eid;
int IntEid;

//added 's' at end of eventDetailsView due to conflicting naming conventions
DetailsView eventDetailsViews = new DetailsView();

public void tasksGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
    eventDetailsView.Visible = true;
    //Get's the currently selected row
    GridViewRow row = tasksGridView.SelectedRow;
    selectedId = row.Cells[1].Text;
    System.Diagnostics.Debug.WriteLine(selectedId);

    Eid = tasksGridView.SelectedRow.Cells[1].Text;
    IntEid = Convert.ToInt32(Eid);

    description = Tquery[IntEid].EventLogs.FirstOrDefault().EventDesc.ToString();
    *///description = Tquery[IntEid].EventLogs.FirstOrDefault().EventDesc;*
    resultCode = Convert.ToInt32(Tquery[IntEid].EventLogs.FirstOrDefault().ResultCode);
    TaskInstanceID = Convert.ToInt32(Tquery[IntEid].EventLogs.FirstOrDefault().TaskInstanceID);

    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3]
        {
            new DataColumn("Eid", typeof(int)),
            new DataColumn("Description", typeof(string)),
            new DataColumn("TaskInstanceID", typeof(int))
        });
    dt.Rows.Add(Eid, description, TaskInstanceID);

    eventDetailsViews.DataSource = dt;
    eventDetailsView.DataBind();

}

这是我的查询代码:

    protected void Page_Load(object sender, EventArgs e)
{
    infordevEntitiesOrbis dbContext = new infordevEntitiesOrbis();
    //Acting as a using SqlConnection to the database
    using (infordevEntitiesOrbis context = new infordevEntitiesOrbis())
    {
        //On pageload, not on user interaction (Occurs regardless)
        if (!IsPostBack)
        {
            d = d.AddMonths(-3);

            //Query written using LINQ
            Tquery = (from tasks in context.Tasks.AsEnumerable()
                      select new Task()
                      {
                          TaskID = tasks.TaskID,
                          TaskName = tasks.TaskName,
                          TaskPath = tasks.TaskPath,
                          Schedules = tasks.Schedules
                      }).ToList();

ASP 网格视图和详细视图的代码:

 <asp:GridView ID="tasksGridView" runat="server" DataKeyNames="TaskID" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" AutoGenerateColumns="False" AutoGenerateSelectButton="True" OnSelectedIndexChanged="tasksGridView_SelectedIndexChanged" OnSelectedIndexChanging="tasksGridView_SelectedIndexChanging" OnRowDataBound="tasksGridView_RowDataBound1" HorizontalAlign="Center">
                <Columns>
                    <asp:BoundField DataField="TaskID" HeaderText="TaskID" ReadOnly="True" SortExpression="TaskID"></asp:BoundField>
                    <asp:BoundField DataField="TaskPath" HeaderText="TaskPath" SortExpression="TaskPath"></asp:BoundField>
                    <asp:BoundField DataField="TaskName" HeaderText="TaskName" SortExpression="TaskName"></asp:BoundField>
                    <asp:TemplateField HeaderText="RunTime">
                        <ItemTemplate>
                            <asp:TextBox ID="UTCRT" runat="server" Enabled="false" BorderStyle="Dotted" BorderWidth="1px" ReadOnly="True"></asp:TextBox>
                            <asp:TextBox ID="UTCLRT" runat="server" Enabled="false" BorderStyle="Dotted" BorderWidth="1px" ReadOnly="True"></asp:TextBox>
                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Wrap="True" />
                    </asp:TemplateField>
                </Columns>
                <FooterStyle BackColor="#CCCC99" ForeColor="Black"></FooterStyle>

                <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White"></HeaderStyle>

                <PagerStyle HorizontalAlign="Right" BackColor="White" ForeColor="Black"></PagerStyle>

                <SelectedRowStyle BackColor="#6699FF" Font-Bold="True" ForeColor="White"></SelectedRowStyle>

                <SortedAscendingCellStyle BackColor="#F7F7F7"></SortedAscendingCellStyle>

                <SortedAscendingHeaderStyle BackColor="#4B4B4B"></SortedAscendingHeaderStyle>

                <SortedDescendingCellStyle BackColor="#E5E5E5"></SortedDescendingCellStyle>

                <SortedDescendingHeaderStyle BackColor="#242121"></SortedDescendingHeaderStyle>
            </asp:GridView>


            <asp:DetailsView ID="eventDetailsView" runat="server" AutoGenerateRows="False">
                <RowStyle HorizontalAlign="Center" />
            </asp:DetailsView>

RowDataBound:

foreach (GridViewRow row in tasksGridView.Rows)
    {
        currentDataIndex = e.Row.RowIndex;
        if (row.RowType == DataControlRowType.DataRow)
        {
            if (utcRnTime != null)
            {
                try
                {
                    utcLRTUpdate = Tquery[currentDataIndex].Schedules.FirstOrDefault().UtcLastRunTime.Value;
                    utcRTUpdate = Tquery[currentDataIndex].Schedules.FirstOrDefault().UtcRunTime.Value;

如有任何帮助,我们将不胜感激! 我认为不需要更多代码。

您似乎正在尝试访问 index Eid 上的 TQuery 列表中的对象,该对象可能不存在(如果 ID 为 13020,它将查看列表中的那个位置)。使用 Tquery.First(t => t.TaskID === Eid).EventLogs... 获取您正在寻找的任务。

您似乎正试图通过任务 ID 在列表中查找任务(我假设 EidIntEidTask.TaskID 相同,但很难判断从你的代码)。您不能使用列表和 [] 属性... 按索引而不是 ID 执行此操作。

也许你应该改用字典:

Tquery = (
             from tasks in context.Tasks.AsEnumerable()
             select new Task()
             {
                 TaskID = tasks.TaskID,
                 TaskName = tasks.TaskName,
                 TaskPath = tasks.TaskPath,
                 Schedules = tasks.Schedules
             }
         )
         .ToDictionary
         (
             task => task.TaskID //Create a dictionary using the TaskID as the key
         );

然后当你这样做时:

description = Tquery[IntEid].EventLogs.FirstOrDefault().EventDesc.ToString();

...您实际上是按 ID 而不是索引查找。

我通过为事件日志创建一个单独的查询 table 并使用查询结果分配变量 'description'、'resultCode' 和 'TaskInstanceID'.[=12 来解决这个问题=]

如您所见,新查询与旧查询几乎相同:

Equery = (from eventLog in context.EventLogs.AsEnumerable()
                  where eventLog.TaskID == IntEid && eventLog.ResultCode != 0 && eventLog.EventType == 2
                  select new EventLog()
                  {
                      TaskID = eventLog.TaskID,
                      EventDesc = eventLog.EventDesc,
                      ResultCode = eventLog.ResultCode,
                      TaskInstanceID = eventLog.TaskInstanceID
                  }).ToList();

然后在这里设置查询结果:

        description = Equery.FirstOrDefault(t => t.TaskID == IntEid).EventDesc.ToString();
        resultCode = Equery.FirstOrDefault(t => t.TaskID == IntEid).ResultCode.ToString();
        TaskInstanceID = Equery.FirstOrDefault(t => t.TaskID == IntEid).TaskInstanceID.ToString();