1

my intention was to switch form an int-represented month value (as it is in database table)

convert it (to display in GridView) as string(month name) and return it back to database as int (covert back to original type, int-represented month).

these are the relevant elements in my 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> 

i was tring using these Helper methods From code Behind

    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;

to achieve this simple task but had few errors i would like to have an example to how is the right way to achieve it. i thought it's simple cause displaying int via

<%# manipulation Function( Eval("columnName")) %>

would "just work"

but it got too complicated for me as newb when trying it with Bind("columnName")

i was wrong by assuming the value was inside Cells[1] when it was actually in Cells[0]

so i do have it in normal mode and also in Edit mode though not editble but via Label as in view mode instead of a TextBox

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** ?
LoneXcoder
  • 2,121
  • 6
  • 38
  • 76

2 Answers2

2

This is what you would do to get a string Month name from an int:

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);

More info here:

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

For converting month number into month name in sql server, look here:

Convert Month Number to Month Name Function in SQL

---- EDIT

OK, on RowDataBound, you would want to convert int to string, so it would be something like:

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)

   }

}

On Row_updating, you want to convert the month name to int again, and then update you dataset (or save to the database)

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();
}
Community
  • 1
  • 1
tranceporter
  • 2,241
  • 1
  • 21
  • 23
  • thanks for info , though the question was not **how to maipulate** rather how to implement the right way sending back value to databse when edited as name need is to return as int as it was originally – LoneXcoder Sep 17 '12 at 08:35
  • Why can't you convert the month number to month name before you databind the gridview? When you fetch data from the database, you can either convert month number to month name in the stored proc itself, or do it in C# before you bind the dataset to the gridview. For editing, you can trap the GridView_onRowEdited event, and convert the string to int using DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month – tranceporter Sep 17 '12 at 08:52
  • that is exactly what i am having the difficulties with : "`trap the GridView_onRowEdited event, and convert the string to int using DateTime.ParseExact`" i already have an event as such , there's my syntax lack of knowledge if i could only have an example for value before update then value after update. – LoneXcoder Sep 17 '12 at 08:58
  • What is the exact problem you are having? Do you get an exception? Also, is it possible for you to pass the month string to the database, and convert it to month number, in the update stored proc? You can use SELECT DATEPART(mm,CAST(monthname+ ' 1, 1900' AS DATETIME)) on sql side to convert the month name to number and store it in table. – tranceporter Sep 17 '12 at 09:03
  • i am using standrt sqlDs with sql parameters as in code above would it be easier using a simple extra line with storedProcidure ? , then again i am not femilier with stored procidure syntax so i wouldn't know implementing it – LoneXcoder Sep 17 '12 at 09:11
  • i will go through my `RowDataBound` event handler again though i think my problem is when switching to `Edit` and sending value back to database so problem is not only display value but converting back to int before the actual update am i missing somthing isn't there the need for it ? – LoneXcoder Sep 17 '12 at 09:28
  • thanks so much for your time gonna try it , and i'll be back to mark your's as right one, if there's no syntax issues with my names it will be easy so i'll be back here soon , Thanks a lot for your help !! – LoneXcoder Sep 17 '12 at 09:35
  • i've updated my question so you can view the RowDataBound as it is,**problem remains before update ** , for starter my problem was guessing the cell no' in array cause after blocking with "readOnly" the pk id of table, the first cell(0) jumped to hold second field i guess thaht was it , but problem remains befor update while In Edit mode it is now a label instaed of TextBox , so you can't edit value for update , it's blocked – LoneXcoder Sep 17 '12 at 10:04
  • Sorry, I am not understanding the comment. The DataBound works fine, and displays the month name as a label. When you edit, it should become a textBox, because you EditItemTemplate has a textBox? Also, you should use the RowUpdating event, not the RowEditing. – tranceporter Sep 17 '12 at 10:22
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16770/discussion-between-lonexcoder-and-tranceporter) – LoneXcoder Sep 17 '12 at 10:49
1

Page class:

private static CultureInfo culture = CultureInfo.CreateSpecificCulture("he-IL");

public static string GetMonthName(string monthNum)
{
    return culture.DateTimeFormat.GetMonthName(Convert.ToInt32(monthNum));
}

GridView:

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

In your EditTemplate have a DropDownList with ListItems: value="1" Text="תשרי" etc.. so that it's the month number that's passed to your data layer for edits.

hollystyles
  • 4,979
  • 2
  • 36
  • 38
  • tried to avoid use of hardCoded item values via DDL , while using 'sophsticated' way which could be used with every form , maybe it's still better to use hardcoded items than textbox edit field – LoneXcoder Sep 17 '12 at 09:08
  • Using DropDownList is a better idea that textbox. DDL will give you control over string names (January. February) etc, where as with textbox, you will have to validate user input, which is additional headache. – tranceporter Sep 17 '12 at 09:12
  • You can still bind the DropDownList if you want with it's own DataSource. – hollystyles Sep 17 '12 at 09:19
  • I think it's the easiest way to implement it , though i will make a helper class with method to populate any given DDL with parameter DDL ddl'sName so hardCoding values will occurs only once and will Suffice for every other time using it in other forms that was the idea – LoneXcoder Sep 17 '12 at 09:21
  • In my apps I just cache the list, you're only going to bind it once for the row that's in edit mode. – hollystyles Sep 17 '12 at 09:27
  • I just tested this in an example app with a SqlDataSource that has insert and update statements configured, and the two-way binding works great. – hollystyles Sep 17 '12 at 10:11
  • sorry for not deciding yet i am trying to learn somthing important here so if i'll see it's taking "years" i'll fall back to using this method , still trying with @tranceporter help maybe i'm questing the wrong method there ? did you follow (?) – LoneXcoder Sep 17 '12 at 10:46
  • I just wanted to be sure, as I have mostly used ObjectDataSources myself, and not the two-way <%# Bind("Property") %> syntax before. It's good your trying the various solutions, ultimately only you can decide what fits best to your apps' architecture and requirements. Ignore us rep-whores and go with what best suits your situation. – hollystyles Sep 17 '12 at 10:56
  • @HollyStyles it did took "years" but i did manage to build it as i wanted , thaks to mr' trance here ! still i have problems with update you're welcome to have rep in my new post for simple task of update which does not work , manipulating the month as requested is going good through all stages includung view edit and update , right till the actual update ! – LoneXcoder Sep 17 '12 at 15:50
  • @HollyStyles eventually , gonna use the DDL on bynding as you suggested i gave up 10 fricking hours when eventually solved issue with update as well but still had a "Input string was not in a correct format." when page i guess tryes rendering again after update i guess "Go with the flow" suits this project and upcomming too thanks alot for this answer of yours sorry i didn't go with this as first option it's my bad . learning ... – LoneXcoder Sep 17 '12 at 21:30