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

时间:2018-11-22 15:36:11

标签: c# asp.net linq gridview detailsview

我收到“索引超出范围错误”,但不是为什么,

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

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

  

错误消息(第50行)

     

第50行:描述=   Tquery [IntEid] .EventLogs.FirstOrDefault()。EventDesc.ToString();

     

第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;

任何帮助将不胜感激! 我认为不需要任何其他代码。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

看起来您正在尝试通过其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而不是索引进行查找。

答案 2 :(得分:0)

我通过为EventLogs表创建一个单独的查询并使用查询结果来分配变量“ description”,“ resultCode”和“ TaskInstanceID”来解决了这个问题。

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

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();