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
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
The data keys is always referenced by name.
So, from the grid it is
(Get the 5th row datakey value of "ID")
In your case, you have the selected row, so you need this: