【问题标题】:gridview column value manipulated操纵gridview列值
【发布时间】:2012-09-09 10:49:24
【问题描述】:

我的意图是转换一个 int 表示的月份值 (因为它在数据库表中)

将它(在 GridView 中显示)转换为字符串(月份名称) 并将其作为 int 返回到数据库(隐回原始类型,以 int 表示的月份)。

这些是我的 GridView 中的相关元素,

<asp:GridView ID="GV_DaysPerMonth" runat="server" DataSourceID="dsWorkDayPerMonth" 
        AutoGenerateColumns="False" DataKeyNames="recordID" AllowPaging="True" 
        CellPadding="4" ForeColor="#333333" GridLines="None" Font-Names="arial" PageSize="12" 
        OnRowDataBound="GV_DaysPerMonth_RowDataBound"
        OnRowEditing="GV_DaysPerMonth_RowEditing"
        OnRowUpdating="GV_DaysPerMonth_RowUpdating">
    <AlternatingRowStyle BackColor="White" />
    <Columns>



                <asp:TemplateField HeaderText="חודש" ControlStyle-Width="100" HeaderStyle-Width="120" ItemStyle-HorizontalAlign="Center"> 
                    <ItemTemplate> 
                        <%# Eval("theMonth")%> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:TextBox ID="TBX_theMonth" runat="server" Text='<%# Bind("theMonth")%>' /> 
                    </EditItemTemplate> 

<asp:GridView ID="GV_DaysPerMonth" runat="server" DataSourceID="dsWorkDayPerMonth" 
        AutoGenerateColumns="False" DataKeyNames="recordID" AllowPaging="True" 
        CellPadding="4" ForeColor="#333333" GridLines="None" Font-Names="arial" PageSize="12" 
        OnRowDataBound="GV_DaysPerMonth_RowDataBound"
        OnRowEditing="GV_DaysPerMonth_RowEditing"
        OnRowUpdating="GV_DaysPerMonth_RowUpdating">
    <AlternatingRowStyle BackColor="White" />
    <Columns>



                <asp:TemplateField HeaderText="Current Month" ControlStyle-Width="100" HeaderStyle-Width="120" ItemStyle-HorizontalAlign="Center"> 
                    <ItemTemplate> 
                        <%# Eval("theMonth")%> 
                    </ItemTemplate> 
                    <EditItemTemplate> 
                        <asp:TextBox ID="TBX_theMonth" runat="server" Text='<%# Bind("theMonth")%>' /> 
                    </EditItemTemplate> 

我在后面的代码中使用这些 Helper 方法

    public static CultureInfo ILci = CultureInfo.CreateSpecificCulture("he-IL");

    public static string GetMonthName(int mInt)
    {
        DateTime fullDate = new DateTime(2012, mInt, 2);
        string[] tempDayArray = fullDate.ToString("MMMM", ILci).Split(' ');
        return tempDayArray[0];
    }
    public static int GetMonthAsInt(string mStr)
    {
        return DateTime.ParseExact(mStr, "MMMM", ILci).Month;

为了完成这个简单的任务,但几乎没有错误,我想举一个例子来说明实现它的正确方法。 我认为这很简单,因为通过

显示 int
<%# manipulation Function( Eval("columnName")) %>

会“正常工作”

但这对我来说太复杂了,因为我是新手 尝试使用 Bind("columnName")

我错误地假设值在 Cells[1] 中,而实际上它在 Cells[0] 中

所以我确实在正常模式下拥有它 并且在编辑模式下虽然不是可编辑但通过标签作为查看模式而不是文本框

protected void GV_DaysPerMonth_RowDataBound(object sender, GridViewRowEventArgs e)
{

    RowNum = GV_DaysPerMonth.Rows.Count;
    GridViewRow CurRow = e.Row;        // Retrieve the current row. 

    if (CurRow.RowType == DataControlRowType.DataRow)
    {
        bool isntEmptyMonth = string.IsNullOrEmpty(e.Row.Cells[0].Text) == false;
        if (isntEmptyMonth)
        {
            e.Row.Cells[1].Text = RobCS.RDates.GetMonthName(Convert.ToInt32((e.Row.Cells[0].Text)));
        }

    }
}


so i think it might be the **missing handler for the edit mode** ?

【问题讨论】:

    标签: c# asp.net datetime gridview


    【解决方案1】:

    这是从 int 中获取字符串月份名称的方法:

    CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
    

    更多信息在这里:

    Best way to turn an integer into a month name in c#?

    要在sql server中将月份数字转换为月份名称,请看这里:

    Convert Month Number to Month Name Function in SQL

    ---- 编辑

    好的,在 RowDataBound 上,您希望将 int 转换为字符串,所以它会是这样的:

    void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
    {
    
       if(e.Row.RowType == DataControlRowType.DataRow)
       {
          // Display the month name. When you GridView is bound for the first time, you 
          // will bind the month number, which you can get in e.Row.Cells[1].Text. If 
         // Cells[1] does not work, try Cells[2], till you get the correct value. The 
         // convert the int to month name and assign it to the same Cell.
         e.Row.Cells[1].Text = GetMonthNameFromInt(e.Row.Cells[1].Text)
    
       }
    
    }
    

    在 Row_updating 上,您想再次将月份名称转换为 int,然后更新您的数据集(或保存到数据库)

    protected void GridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {    
    
       //Update the values.
       GridViewRow row = GridView.Rows[e.RowIndex];
       var monthName = ((TextBox)(row.Cells[1].Controls[0])).Text;
       var monthNumber = GetMonthNumber(monthName);
    
      // code to update your dataset or database with month number 
    
      //Reset the edit index.
      GridView.EditIndex = -1;
    
      //Bind data to the GridView control.
      BindData();
    }
    

    【讨论】:

    • 感谢您的信息,尽管问题不是 如何处理,而是如何实现在根据名称需要进行编辑时将值发送回数据库的正确方法是以 int 形式返回原来是
    • 为什么不能在对 gridview 进行数据绑定之前将月份编号转换为月份名称?当您从数据库中获取数据时,您可以在存储过程本身中将月份编号转换为月份名称,或者在将数据集绑定到 gridview 之前在 C# 中执行此操作。对于编辑,您可以捕获 GridView_onRowEdited 事件,并使用 DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month 将字符串转换为 int
    • 这正是我遇到的困难:“trap the GridView_onRowEdited event, and convert the string to int using DateTime.ParseExact”我已经有一个这样的事件,如果我在更新之前只能有一个值示例,那么我的语法缺乏知识更新后的值。
    • 您遇到的具体问题是什么?你有例外吗?另外,您是否可以在更新存储过程中将月份字符串传递给数据库,并将其转换为月份编号?您可以在 sql 端使用 SELECT DATEPART(mm,CAST(monthname+ ' 1, 1900' AS DATETIME)) 将月份名称转换为数字并将其存储在表中。
    • 我正在使用带有 sql 参数的标准 sqlDs,如上面的代码所示,使用带有 storedProcidure 的简单额外行会更容易吗? ,然后我又不熟悉存储过程语法,所以我不知道实现它
    【解决方案2】:

    页面类:

    private static CultureInfo culture = CultureInfo.CreateSpecificCulture("he-IL");
    
    public static string GetMonthName(string monthNum)
    {
        return culture.DateTimeFormat.GetMonthName(Convert.ToInt32(monthNum));
    }
    

    网格视图:

        <ItemTemplate> 
            <%# GetMonthName(Eval("theMonth").ToString())%> 
        </ItemTemplate> 
        <EditItemTemplate>
            <asp:DropDownList ID="ddlMonth" runat="server" SelectedValue='<%# Bind("theMonth")%>'>
                <asp:ListItem Value="1" Text="תשרי"></ListItem>
                   etc...
            </asp:DropDownList>
       </EditItemTemplate>
    

    在您的 EditTemplate 中有一个带有 ListItems 的 DropDownList:value="1" Text="תשרי" 等。因此它是传递给您的数据层进行编辑的月份编号。

    【讨论】:

    • 试图通过 DDL 避免使用硬编码项目值,同时使用可用于每个表单的“复杂”方式,也许使用硬编码项目比使用文本框编辑字段更好
    • 使用 DropDownList 比文本框更好。 DDL 将让您控制字符串名称(1 月、2 月)等,而对于文本框,您将不得不验证用户输入,这更加令人头疼。
    • 如果你想用它自己的数据源,你仍然可以绑定 DropDownList。
    • 我认为这是实现它的最简单方法,尽管我将创建一个辅助类,其方法是使用参数 DDL ddl'sName 填充任何给定的 DDL,因此硬编码值只会出现一次,并且足以满足每个其他时候以其他形式使用它是这个想法
    • 在我的应用程序中,我只是缓存列表,您只需为处于编辑模式的行绑定一次。
    猜你喜欢
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    相关资源
    最近更新 更多