按下编辑链接后控件消失

时间:2014-05-27 08:40:03

标签: c# asp.net

我有一个网格,按下按钮后会填充数据。

它包含某个月的每一天的列:

Image 1

当用户按下“编辑”按钮时,我希望标签(显示文本dayLabelText)被控件替换,以便输入该月当天特定值的数据。

但是当我按下编辑按钮时,所有控件都会消失:

Image 2

当我按下取消按钮时,没有任何变化。

Image 3

我应该如何修改下面显示的代码以修复此错误(当我按下编辑时,应该显示下拉列表,当我按下取消 - 文本字段时)?

* .aspx文件:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="plan.aspx.cs" Inherits="plan" 
    EnableViewState="true" ViewStateMode="Enabled"  %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server" EnableViewState="true" ViewStateMode="Enabled">

    [...]

    <asp:GridView 
        ID="dailyPlanGrid" 
        runat="server" 
        OnRowCancelingEdit="dailyPlanGrid_RowCancelingEdit" 
        OnRowEditing="dailyPlanGrid_RowEditing"
        AutoGenerateColumns="False" OnRowDataBound="dailyPlanGrid_RowDataBound">
        <Columns>
            <asp:TemplateField HeaderText="Edit" ShowHeader="False" HeaderStyle-HorizontalAlign="Left"> 
                <EditItemTemplate> 
                    <asp:LinkButton ID="lbkUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton> 
                    <asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton> 
                </EditItemTemplate> 
                <ItemTemplate> 
                    <asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton> 
                </ItemTemplate> 
            </asp:TemplateField> 
            <asp:TemplateField HeaderText="">
                <EditItemTemplate>
                    <asp:Label ID="titleLabelEdit" runat="server" Text='<%# Bind("Title") %>' />
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="titleLabelItem" runat="server" Text='<%# Bind("Title") %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
 </asp:Content>

.aspx.cs文件:

public partial class plan : System.Web.UI.Page
{

    [...]

    private void UpdateGrid(int year, int month, string userName, bool updateTableCall = false)
    {
        [...]

        DisplaySelectedPlan(year, month, userName, updateTableCall);
    }

    private void DisplaySelectedPlan(int year, int month, string userName, bool updateTableCall = false)
    {
        DataTable data = new DataTable();

        DataColumn titleColumn = new DataColumn();

        titleColumn.ColumnName = "Title";
        titleColumn.Caption = "";

        data.Columns.Add(titleColumn);

        INumberOfDaysInMonthCalculator numberOfDaysInMonthCalculator = new NumberOfDaysInMonthCalculator();        

        int daysInMonth = numberOfDaysInMonthCalculator.GetNumberOfDays(year, month);

        if (updateTableCall)
        {
            AddDayColumns(daysInMonth);
        }

        var row = data.NewRow();
        row["Title"] = "Вид";
        data.Rows.Add(row);

        Database.Instance.Open();

        IDailyWorkingTimesReader dailyWorkingTimesReader = new DailyWorkingTimesReader(Database.Instance.SqlCommandFactory);

        dailyWorkingTimesReader.ReadData(year, month, userName);

        IDictionary<int, DateTime> startTimesByDay = dailyWorkingTimesReader.GetStartTimes();
        IDictionary<int, DateTime> endTimesByDay = dailyWorkingTimesReader.GetEndTimes();

        AddStartRow(data, daysInMonth, startTimesByDay);
        AddEndRow(data, daysInMonth, endTimesByDay);

        var holidayRow = data.NewRow();
        holidayRow["Title"] = "Госудаственный праздник";
        data.Rows.Add(holidayRow);

        var preHolidayRow = data.NewRow();
        preHolidayRow["Title"] = "Предпраздничный день";
        data.Rows.Add(preHolidayRow);

        dailyPlanGrid.ShowHeaderWhenEmpty = true;

        dailyPlanGrid.DataSource = data;
        dailyPlanGrid.DataBind();
    }

    private void AddDayColumns(int daysInMonth)
    {
        for (int i = 1; i <= daysInMonth; i++)
        {
            TemplateField dayColumn = new TemplateField();

            dayColumn.HeaderText = "" + i;
            dayColumn.EditItemTemplate = new DayEditItemTemplate(i);
            dayColumn.ItemTemplate = new DayItemTemplate(i);

            dailyPlanGrid.Columns.Add(dayColumn);
        }

    }

    private static void AddEndRow(DataTable data, int daysInMonth, IDictionary<int, DateTime> endTimesByDay)
    {
        var endRow = data.NewRow();
        endRow["Title"] = "Конец";

        FillTimeColumns(daysInMonth, endRow, endTimesByDay);

        data.Rows.Add(endRow);
    }

    private static void AddStartRow(DataTable data, int daysInMonth, IDictionary<int, DateTime> startTimesByDay)
    {
        var startRow = data.NewRow();
        startRow["Title"] = "Начало";

        FillTimeColumns(daysInMonth, startRow, startTimesByDay);
        data.Rows.Add(startRow);
    }

    private static void FillTimeColumns(int daysInMonth, DataRow row, IDictionary<int, DateTime> timesByDay)
    {
        for (int i = 1; i <= daysInMonth; i++)
        {
            if (timesByDay.ContainsKey(i))
            {
                row["Day" + i] = timesByDay[i];
            }
        }
    }

    private void CreatePlanForSelectedEmployeeAndMonth(int year, int month, string userName)
    {
        IDailyPlanCreator dailyPlanCreator = new DailyPlanCreator(Database.Instance.SqlCommandFactory, 
            new NumberOfDaysInMonthCalculator());
        Database.Instance.Open();
        dailyPlanCreator.CreateDailyPlan(year, month, userName);
    }
    protected void updateTableButton_Click(object sender, EventArgs e)
    {
        // Here the grid is initialized (after the user presses some button)

        DataTable dataTable = monthList.DataSource as DataTable;
        DataRow row = dataTable.Rows[monthList.SelectedIndex] as DataRow;
        IUserNameExtractor userNameExtractor = new UserNameExtractor();

        UpdateGrid((int)row["year"], (int)row["month"], userNameExtractor.ExtractUserNameWithoutDomain(Request.LogonUserIdentity.Name), true);
    }
    protected void dailyPlanGrid_RowEditing(object sender, GridViewEditEventArgs e)
    {
        dailyPlanGrid.EditIndex = e.NewEditIndex;

        DataTable dataTable = monthList.DataSource as DataTable;
        DataRow row = dataTable.Rows[monthList.SelectedIndex] as DataRow;
        IUserNameExtractor userNameExtractor = new UserNameExtractor();

        UpdateGrid((int)row["year"], (int)row["month"], userNameExtractor.ExtractUserNameWithoutDomain(Request.LogonUserIdentity.Name));
    }
    protected void dailyPlanGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        dailyPlanGrid.EditIndex = -1;

        DataTable dataTable = monthList.DataSource as DataTable;
        DataRow row = dataTable.Rows[monthList.SelectedIndex] as DataRow;
        IUserNameExtractor userNameExtractor = new UserNameExtractor();

        UpdateGrid((int)row["year"], (int)row["month"], userNameExtractor.ExtractUserNameWithoutDomain(Request.LogonUserIdentity.Name));
    }
    protected void dailyPlanGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if ((e.Row.RowType == DataControlRowType.DataRow) && (dailyPlanGrid.EditIndex > -1))
        {
            DataTable dataTable = monthList.DataSource as DataTable;
            DataRow row = dataTable.Rows[monthList.SelectedIndex] as DataRow;

            int year = (int)row["year"];
            int month = (int)row["month"];

            INumberOfDaysInMonthCalculator numberOfDaysInMonthCalculator = new NumberOfDaysInMonthCalculator();        

            int daysInMonth = numberOfDaysInMonthCalculator.GetNumberOfDays(year, month);


            if (e.Row.RowIndex == 0)
            {
                // Type
                for (int i=1; i <= daysInMonth; i++)
                {
                    DropDownList dropDownList = (DropDownList) e.Row.FindControl("dayDropDownList" + i);

                    if (dropDownList != null)
                    {
                        dropDownList.Items.Clear();

                        dropDownList.Items.Add("item1");
                        dropDownList.Items.Add("item2");
                    }
                }
            }
            else if (e.Row.RowIndex == 1)
            {
                // Start time of the business day
            }
            else if (e.Row.RowIndex == 2)
            {
                // End time of the business day
            }
            else if (e.Row.RowIndex == 3)
            {
                // Holiday
            }
            else if (e.Row.RowIndex == 4)
            {
                // Pre-holiday
            }
        }
    }
}

请注意,所有日期的列都是以编程方式添加的。必须以这种方式完成,因为

  1. 客户希望将日期显示在列中(每天一列,而不是每天一行)和
  2. 特定月份的天数不同。
  3. 因此,我在列中添加了两种模板 - 一种用于显示,另一种用于编辑与日期相关的数据。

    private void AddDayColumns(int daysInMonth)
    {
        for (int i = 1; i <= daysInMonth; i++)
        {
            TemplateField dayColumn = new TemplateField();
    
            dayColumn.HeaderText = "" + i;
            dayColumn.EditItemTemplate = new DayEditItemTemplate(i);
            dayColumn.ItemTemplate = new DayItemTemplate(i);
    
            dailyPlanGrid.Columns.Add(dayColumn);
        }
    
    }
    

    DayEditItemTemplate.cs:

    public class DayEditItemTemplate : ITemplate
    {
        private readonly int day;
    
        public DayEditItemTemplate(int aDay)
        {
            day = aDay;
        }
    
        public void InstantiateIn(Control container)
        {
            DropDownList dropDownList = new DropDownList();
            dropDownList.ID = "dayDropDownList"+day;
            dropDownList.Items.Add("item1"); 
            dropDownList.Items.Add("item2");
            dropDownList.Items.Add("item3");
            container.Controls.Add(dropDownList);
        }
    }
    

    DayItemTemplate.cs:

    public class DayItemTemplate : ITemplate
    {
        private readonly int day;
    
        public DayItemTemplate(int aDay)
        {
            day = aDay;
        }
    
        public void InstantiateIn(Control container)
        {
            Label dayLabel = new Label();
            dayLabel.ID = "dayLabelText"+day;
            dayLabel.Text = "dayLabelText";
            container.Controls.Add(dayLabel);
        }
    }
    

    更新1:该错误与我以编程方式添加面向日期的控件有关。

    理由:当我在** .aspx *文件中的列时,问题不会发生(使用该特定列)。

            <asp:TemplateField HeaderText="DayX">
                <EditItemTemplate>
                    <asp:DropDownList ID="dayXdropDownList" runat="server" />
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="dayXLabel" Text="dayXLabel" runat="server"  />
                </ItemTemplate>
            </asp:TemplateField>
    

1 个答案:

答案 0 :(得分:0)

您需要为每列添加EditItemTemplate并按以下方式绑定它,

<EditItemTemplate>
        <asp:Label ID="titleLabelEdit" runat="server" Text='<%# Bind("Title") %>' />
</EditItemTemplate>