skip to Main Content

I develop one web form by using ASP.net, I want to select the row and display that row data into web form but the date cannot display in the textbox of type DateTime, someone helps me to sort out this issue

ASP.Net Code

<div class="col-4">
    <asp:Label ID="Label7" runat="server" Text="Birth Date"></asp:Label>
    <asp:TextBox ID="txtBirthDate" runat="server" TextMode="Date"></asp:TextBox>
    </br>
    <asp:Button ID="btnSave" Text="Save" runat="server" OnClick="btnSave_Click" />
</div>
<div class="col-8">
    <asp:GridView ID="studentGrid" runat="server"
        DataKeyNames="Id"
        OnSelectedIndexChanged="StudentGrid_SelectedIndexChanged">
        <Columns>
            <asp:CommandField ButtonType="Button" ShowSelectButton="True" />
        </Columns>
    </asp:GridView>
</div>

c# Code

protected void StudentGrid_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        selId = Convert.ToInt16(studentGrid.SelectedDataKey[0]);

        if (selId > 0)
        {
            using (var ctx = new dbTestEntities())
            {
                var oldObj = ctx.tblStudents.Find(selId);
                if (oldObj != null)
                {
                    txtBirthDate.Text = oldObj.BirthDate.ToString();
                }
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    Date format of the textbox with TextMode="Date" is "yyyy/MM/dd" but it stores date with default time like 2021/25/09 12:00:00 AM so the date is fetched from database but not able to set to the textbox, So we need to set the proper format of date like

    
        txtBirthDate.Text = String.Format("{0:yyyy/MM/dd}", oldObj.BirthDate);
    
    

  2. The data keys is always referenced by name.

    So, from the grid it is

     GridView1.DataKeys[5]["ID"]
    

    (Get the 5th row datakey value of "ID")

    In your case, you have the selected row, so you need this:

    selId = Convert.ToInt16(studentGrid.SelectedDataKey["ID"]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search