I am attempting to use the code-behind (Page_Load or PreRender) to set a date-time textbox in a DetailsView so that it defaults to a current date-time.
What I have attempted is (one of many variations):
protected void DetailsView2_PreRender(object sender, EventArgs e)
{
((TextBox)DetailsView2.FindControl("date_time")).Text =
DateTime.Now.ToString("d");
}
But all that I get is a 'NullReferenceException' error.
What I am doing wrong?
You can use detailsview controls DataBound event to set a value within your detailsview like that :
<asp:Label ID="DetailsView2" runat="server" OnDataBound="DetailsView2_DataBound">
</asp:Label>
Code Behind :
protected void DetailsView2_DataBound(object sender, EventArgs e)
{
DetailsView myDetailsView = (DetailsView)sender;
if(myDetailsView.CurrentMode == DetailsViewMode.Edit)
{
((TextBox)myDetailsView.FindControl("date_time")).Text = DateTime.Now.ToString("d");
}
}
To add to what Canavar suggested:
For use on a DetailsView assign like this:
<asp:DetailsView ID="DetailsView2" runat="server" AutoGenerateRows="False"
CellPadding="4" DataKeyNames="details_id" DataSourceID="SqlDataSource4"
DefaultMode="Insert" ForeColor="#333333" GridLines="None" Height="50px"
Width="125px"
AllowPaging="True" OnPreRender="DetailsView2_DataBound">
And then in the code behind:
protected void DetailsView2_DataBound(object sender, EventArgs e)
{
DetailsView myDetailsView = (DetailsView)sender;
//Edit
if (myDetailsView.CurrentMode == DetailsViewMode.Edit)
{
((TextBox)myDetailsView.FindControl("TextBox2")).Text = DateTime.Now.ToString("g");
}
//Insert
else if (myDetailsView.CurrentMode == DetailsViewMode.Insert)
{
((TextBox)myDetailsView.FindControl("TextBox2")).Text = DateTime.Now.ToString("M/d/yyyy HH:mm");
}
}
Related
I'm seeing this behavior on two of my pages, but I'm just going to ask about the one that's more important to me at the moment. I have a page that loads information from a database into a ASP gridview and then allows the user to add a detail to each populated line.
The issue I'm having is that when the 'Edit' button of the gridview and then subsequently the 'Update' or 'Cancel' button, it takes two click to actually fire the onclick event. A post back does take place on the first click, but nothing actually happens.
I'm including the code that seems relevant below. The page uses a master page and there are a number of divs involved with formatting, I'm excluding those.
Gridview and related controls:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label Text="Plant Selector: " runat="server" />
<asp:DropDownList ID="ddlPlant" OnSelectedIndexChanged="ddlPlant_SelectedIndexChanged" runat="server" />
<asp:Button ID="btnUpdate" Text="Update" OnClick="btnUpdate_Click" runat="server" />
<p />
<asp:Label ID="lblTest" Text="" runat="server" />
<asp:Label ID="lblerror" Text="" ForeColor="Red" runat="server" />
<asp:GridView ID="gridview1" AutoGenerateColumns="false" runat="server" OnRowEditing="gridview1_RowEditing" OnRowCancelingEdit="gridview1_RowCancelingEdit" OnRowUpdating="gridview1_RowUpdating">
<Columns>
<asp:BoundField DataField="JobNum" HeaderText="Job Number" ReadOnly="true" />
<asp:BoundField DataField="ModelNum" HeaderText="Model" ReadOnly="true" />
<asp:BoundField DataField="Customer" HeaderText="Customer" ReadOnly="true" />
<asp:BoundField DataField="SchCompDate" HeaderText="Sch Comp Date" ReadOnly="true" />
<asp:TemplateField HeaderText="Details">
<EditItemTemplate>
<asp:TextBox ID="Txt" Width="98%" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label Text="Click Edit to add details of exception." runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gridview1" />
</Triggers>
</asp:UpdatePanel>
Sample image below:
Here is the code behind:
private string Plant { get; set; }
// This sets the default plant based off IP.
protected void Page_PreInit(Object sender, EventArgs e)
{
getPlantFromIP();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateDDL();
BindData();
}
else
{
Plant = ddlPlant.SelectedValue.ToString();
}
}
// Populates the drop down.
private void populateDDL()
{
ddlPlant.Items.Add("NC");
ddlPlant.Items.Add("WA");
setPlantInDDL();
}
private void setPlantInDDL()
{
if(Plant == "WA")
{
ddlPlant.SelectedIndex = 1;
}
if (Plant == "NC")
{
ddlPlant.SelectedIndex = 0;
}
}
private void getPlantFromIP()
{
if (Request.ServerVariables["REMOTE_ADDR"] == "70.103.118.100")
{
Plant = "WA";
//ddlPlant.SelectedIndex = 1;
}
else
{
Plant = "NC";
//ddlPlant.SelectedIndex = 0;
}
}
// Database Query.
private DataTable getDataFromDatabase()
{
DataTable rTable = new DataTable();
string plant = ddlPlant.SelectedValue.ToString();
using (var conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["workorderConnectionString"].ConnectionString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
try
{
cmd.CommandText = #"SELECT * FROM reportdatatables.compliance_exception_report
WHERE ExceptionNoted = '0' AND Plant = #plant";
cmd.Parameters.AddWithValue("#plant", plant);
MySqlDataReader reader = cmd.ExecuteReader();
rTable.Load(reader);
reader.Close();
cmd.Dispose();
}
catch
{
}
finally
{
conn.Close();
}
}
}
return rTable;
}
// Binds the data from the database to the gridview.
private void BindData()
{
DataTable data = getDataFromDatabase().Copy();
gridview1.DataSource = data;
gridview1.DataBind();
}
protected void ddlPlant_SelectedIndexChanged(object sender, EventArgs e)
{
//Plant = ddlPlant.SelectedValue.ToString();
BindData();
}
// On edit call.
protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
// On cancel call.
protected void gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridview1.EditIndex = -1;
}
protected void gridview1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
BindData();
}
Here's what I've tried:
-A lot of posts a read saw this behavior relating to autopostback settings of controls. As you can see I'm made sure to not have any control with the autopostback set to true.
-I had some concern that the behavior might be related to the updatepanel, but removing it doesn't change the behavior at all.
-I read that having AutoEventWireup="true" in your page tag can cause this. I DO have that in my page tag, but setting it to false does not fix the issue and prevents my dropdown from being populated on page load.
-There was another post that suggested the ID of the control could be changing between page load and post back. I monitored the IDs of those controls and I do not see any change in their ID.
So all that being said, I'm hoping someone has a clue as to what I'm missing. If there is any more information I can provide that might help, please let me know.
Thank you in advance.
Try this, which will make the grid editable
protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
for cancel also
protected void gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridview1.EditIndex = -1;
BindData();
}
Code Behind
public void lbDelete_Click(object sender, EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow gvrow = lb.NamingContainer as GridViewRow;
gvsize.DeleteRow(gvrow.RowIndex);
}
GridView:
<asp:GridView ID="gvsize" runat="server" ShowFooter="True" CellPadding="1" CellSpacing="2" AutoGenerateColumns="false" GridLines="Horizontal">
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" ForeColor="Blue" OnClick="lbDelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView >
There are 2 rows in my gridview which I need to delete the row using the function above.
It throws an error "gvsize" RowDeletingEvent was not handled properly.
Is that necessary to use OnRowDeleted/OnRowDeleting in gridview which I feel not necessary??
As stated in How to delete row from gridview?
You are deleting the row from the gridview but you are then going and
calling databind again which is just refreshing the gridview to the
same state that the original datasource is in.
Either remove it from the datasource and then databind, or databind
and remove it from the gridview without redatabinding.
You can use row databound event to accomplish this task.
<asp:LinkButton ID="lnkBtnDel" runat="server" CommandName="DeleteRow" OnClientClick="return confirm('Are you sure you want to Delete this Record?');"">Delete</asp:LinkButton>
and in the rowdatabound event you can have
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
//followed by your code
}
}
Try this to delete row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
}
You can also delete row from another method using Template Column
ASPX
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CommandName="deletenotice" ImageUrl="~/images/delete1.gif" alt="Delete"
OnClientClick="return confirm('Are you sure want to delete the current record ?')">
</asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
C# Code
protected void gvNoticeBoardDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower().Equals("deletenotice"))
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
NoticeBoard notice = new NoticeBoard();
HiddenField lblCust = (HiddenField)row.FindControl("hdngvMessageId");//Fetch the CourierId from the selected record
auditTrail.Action = DBAction.Delete;
Service simplyHRClient = new Service();
MessageClass messageClass = simplyHRClient.SaveNoticeBoard(notice, auditTrail);
if (messageClass.IsSuccess)
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "success-message";
if (messageClass.RecordId != -1)
lblCust.Value = messageClass.RecordId.ToString();
}
else
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "fail-message";
}
//Bind Again grid
GetAllNoticeBoard();
}
}
Hope it helps you
I have an ASP.NET website where I have to show some data on a Gridview, I need this data to be shown as fast as possible, so I decided to create a timer inside an Update panel and then Refresh the grid over and over, however I see that my timer is not waiting until it was done in order to Tick again, it's executing itself over and over, which is giving me performance issues on the database, how can I tell my timer "hey stop until this process is done, then continue".
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="400" OnTick="Timer1_Tick" EnableViewState="False">
</asp:Timer>
<asp:GridView ID="gv_stats" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" ShowHeaderWhenEmpty="True" GridLines="Vertical" Width="562px" OnRowDataBound="gv_stats_RowDataBound" ShowFooter="True" EnableViewState="False" >
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
I tried this:
private bool is_refreshing = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Timer1.Enabled = false;
if(is_refreshing == false)
BindGrid();
Timer1.Enabled = true;
}
public void BindGrid()
{
is_refreshing = true;
grd.datasource = con.executedt;
grd.databind();
is_refreshing = false;
}
When you refresh the grid, you can set a private boolean variable indicating the that the grid is refreshing and before the execution of code that refreshes the grid, you can check this variable.
EDIT - Try using a session variable instead of a private variable. See updated example.
Example -
// code change starts
private bool _isGridRefreshing
{
get
{
var flag = HttpContext.Current.Session["IsGridSession"];
if(flag != null)
{
return (bool)flag;
}
return false;
}
set
{
HttpContext.Current.Session["IsGridSession"] = value;
}
}
// code change ends
protected void Timer1_Tick(object sender, EventArgs e)
{
if(_isGridRefreshing == false)
{
RefreshGrid();
}
}
private void RefreshGrid()
{
_isGridRefreshing = true;
//code to refresh the grid.
}
Note - I haven't tested the code, but it should give a fair idea of what needs to be done.
I have read several other questions similar to this, and it looks to be a databinding issue. My issue somehow differs as I do not bind the data on page load. The data is bound when a selection is made from another table on the same page.
For example, my page has 3 tables (one with no value initially):
Sessions - Each session has a session date and a list of attendees
PlayersList - Contains records for all players
Attendees - Displays a list of players for a SELECTED session, from the Sessions table
Each time I select a session, and then check the Attendees checkbox, the value is always 'False'.
Thanks in advance
Here's my code.
Matches.aspx.cs
public partial class Matches : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridSessionsList_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridAttendees_SelectedIndexChanged(object sender, EventArgs e)
{
// this will remove an attendee from the list
}
protected void ButtonUpdatePaid_Click1(object sender, EventArgs e)
{
Session editSession = new Session();
foreach (GridViewRow row in GridAttendees.Rows)
{
editSession.Date = Convert.ToDateTime(GridSessionsList.SelectedValue);
int PlayerID = Convert.ToInt32(row.Cells[1].Text);
bool Paid = Convert.ToBoolean(row.FindControl("Chk") as TextBox);
editSession.UpdateAttendeeList(PlayerID, Paid);
}
}
protected void GridPlayersList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
Session editSession = new Session();
editSession.Date = Convert.ToDateTime(GridSessionsList.SelectedValue);
int PlayerID = Convert.ToInt32(GridPlayersList.SelectedRow.Cells[1].Text);
editSession.UpdateAttendeeList(PlayerID);
GridAttendees.DataBind();
LabelError.Text = "Player has been added to the game on .";
}
catch
{
LabelError.Text = "Something went wrong.. Ensure you have a game selected.";
}
}
public void Chk_OnCheckedChanged(object sender, EventArgs e)
{
}
And here's the Attendees GridView extract from the aspx page:
<asp:GridView ID="GridAttendees" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource2" CssClass="Table" DataKeyNames="PlayerID" OnSelectedIndexChanged="GridAttendees_SelectedIndexChanged">
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Select"/>
<asp:BoundField DataField="PlayerID" HeaderStyle-CssClass = "hideGridColumn" ItemStyle-CssClass="hideGridColumn" HeaderText="PlayerID" SortExpression="PlayerID" InsertVisible="False" ReadOnly="True" >
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="Chk" runat="server" OnCheckedChanged="Chk_OnCheckedChanged" AutoPostBack="True" Checked='<%# Bind("Paid") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="TableHeader" />
<SelectedRowStyle BackColor="Silver" />
</asp:GridView>
I think you are casting your CheckBox as a TextBox ?
Here:
bool Paid = Convert.ToBoolean(row.FindControl("Chk") as TextBox);
Try this:
CheckBox cb = (CheckBox)row.FindControl("Chk");
bool Paid = cb.Checked;
I have gridview in an asp.net application. I want to insert a column with image buttons where by click on it will enable or disable users or change the status field in db and also change the image button image accordingly user status.
Meaning: I want to display different images for disabled and enabled users.
How can I do this in C# and bind the data to the image button?
Anyone please help. Thanks in advance.
Make use of the ItemDataBound event. This is where you can check each row of your grid and apply changes to it. Then you can hide / unhide or change buttons:
VB.net below but you can easily convert to C#:
Dim ib As ImageButton = CType(e.Item.FindControl("ibFav"), ImageButton)
ib.Visible = False
Dim ib2 As ImageButton = CType(e.Item.FindControl("ibRemFav"), ImageButton)
ib2.Visible = True
Sample User Model:
public class UserModel {
public string Name { get; set; }
public bool IsEnabled { get; set; }
}
Here is the GridView Code:
<asp:GridView ID="GridView" runat="server" AutoGenerateColumns="false"
onrowcommand="GridView_RowCommand" onrowdatabound="GridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:ImageButton ID="EnabledImgBtn" runat="server"
CommandArgument='<%# Eval("Name") %>'
CommandName="ResetUserState" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
//Other columns....
</Columns>
</asp:GridView>
Set the 'CommandArgument' according to your needs. e.g the ID of the User.
Sample Code-behind for the gridview:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack){
LoadGridView();
}
}
private void LoadGridView()
{
this.GridView.DataSource = GetUsersFromDatabase();
this.GridView.DataBind();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var user = e.Row.DataItem as UserModel;
var enabledImgBtn = e.Row.FindControl("EnabledImgBtn") as ImageButton;
if (enabledImgBtn != null)
enabledImgBtn.ImageUrl = user.IsEnabled ? "~/YourImagePath/enabled.png"
: "~/YourImagePath/disalbed.png";
}
}
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ResetUserState")
{
if (e.CommandArgument!= null)
{
var userName = e.CommandArgument.ToString();
//Change user enabled state and Update database
//Sample code:
var user = FindUserByName("userName");
user.IsEnabled = !user.IsEnabled;
//SaveInDatabase(user);
LoadGridView();
}
}
}
You may consider using 'CommandField' with Type equal to 'Image' instead of 'TemplateField', but there is an issue with this approach, read more.
Hope this helps.
<asp:GridView ID="GridView" runat="server" AutoGenerateColumns="false"
onrowcommand="GridView_RowCommand" onrowdatabound="GridView_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Change Status" ItemStyle-CssClass="GrdItemImg">
<ItemTemplate>
<asp:ImageButton ID="ibtnChangeActiveStatus" CommandArgument='<%#Eval("RecordID")%>'
CommandName='GRDSTATUS' runat="server" ImageUrl='<%# getStatusImage(Convert.ToInt32(DataBinder.Eval(Container.DataItem,"IsApproved"))) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Col2" HeaderText="Col2" />
//Other Respective columns....
...........
..........
</Columns>
</asp:GridView>
And In CS file add the following function.
public string getStatusImage(int intStatus)
{
string strStatus = string.Empty;
if (intStatus == 1)
{
strStatus = "~/images/active.png";
}
else
{
strStatus = "~/images/inactive.png";
}
return strStatus;
}
So on the base of "intStatus" respective active / InActive Image will be set.