Add Event on specific control in the gridview - c#

I have a scenario, where i need to attach an event (textchanged) to a textbox. It should only trigger, if the code is "code2". Please check the below code ; The value_TextChanged doesn't get triggered:
<asp:GridView runat="server" ID="gv1" AutoGenerateColumns="false"
onrowcreated="gv1_RowCreated1" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="code" Text='<%# Bind("[code]") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" ID="val" Text='<%# Bind("[value]") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
void DataBind()
{
DataTable dt = new DataTable();
dt.TableName = "tb1";
dt.Columns.Add("code");
dt.Columns.Add("value");
dt.Rows.Add("code1", "Red");
dt.Rows.Add("code2", "Green");
dt.Rows.Add("code3", "Blue");
gv1.DataSource = dt;
gv1.DataBind();
}
protected void gv1_RowCreated1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string code = (String)DataBinder.Eval(e.Row.DataItem, "code");
TextBox value = (TextBox)e.Row.FindControl("val");
if (code == "code2")
{
value.AutoPostBack = true;
value.TextChanged += new EventHandler(value_TextChanged);
}
}
}
void value_TextChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}

To trigger TextChange you need to add AutoPostBack="true" in your Markup; For attaching an event with TextChange you need not to depend gv1_RowCreated that also you can specify in the markup.
<asp:TextBox AutoPostBack="true" OnTextChanged="value_TextChanged"
runat="server" ID="val" Text="" ></asp:TextBox>
Please note one more thing, the event will trigger when the textBox
loss its focus

Related

CheckedChanged Event Not Firing In Gridview

I have a gridview in which I have manually generated a column for checkboxes as a HeaderTemplate as below
<asp:GridView ID="gvDB" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" OnRowDataBound="gvDB_RowDataBound" <asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkSelectHeader" AutoPostBack="true" OnCheckedChanged="chkSelectHeader_CheckedChanged" runat="server"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" AutoPostBack="true" runat="server" OnCheckedChanged="chkSelect_CheckedChanged1" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And OnRowDataBound I'm dynamically generating controls and adding it to the each row
e.Row.Cells[rowIndex].Controls.Add(control);
And they are binding to the columns as expected.But my chkSelectHeader_CheckedChanged chkSelect_CheckedChanged1 events are not firing.
Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
AddTemplatesToGrid();
}
BindDataToGridView();
}
public void AddTemplatesToGrid()
{
DataTable dt = new DataTable();
foreach (Employees emp in EmployeesList)
{
TemplateField tfield = new TemplateField();
tfield.HeaderText = emp.Name;
gvDataEntry.Columns.Add(tfield);
}
}
You call BindDataToGridView on every postback which will discard events.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
AddTemplatesToGrid();
}
BindDataToGridView();
}
Include BindDataToGridView() in the !Page.IsPostBack-check.

ADO.net Entity Gridview is null when RowUpdating event fired

So I'm using ADO.net Entity Data model in an ASP.Net (C#) Web page. I am dynamically adding and retrieving data to my database using gridviews. I am using master pages, and my gridview is in a contentplaceholder. My only issue with this code is that when my RowUpdating event fires, the gridview is null. I can call by BindGV function, and then the rest of the code updates the database perfectly fine, with the original data from the database I just bound to it, since the database was not updated yet. In all events, if I change bindGV() to Gridview1.databind(), the gridview is null. I think the datasource the gridview is referencing is becoming null at the end of the event when the data connection is closed, is there anyway to prevent this?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
onrowdatabound="GridView1_RowDataBound"
>
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Machine">
<ItemTemplate>
<asp:Label ID="lblMachine" runat="server" Text='<%# Eval("MachineName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtMachine" runat="server" Text='<%# Eval("MachineName") %>'></asp:TextBox>
</EditItemTemplate>
<ControlStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:Label ID="lblDept" runat="server" Text='<%# Eval("WorkCenterFK") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddldept" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
<ControlStyle Width="120px" />
</asp:TemplateField>
<asp:CommandField HeaderText="Actions" ShowEditButton="true" ShowDeleteButton="True"
ControlStyle-Width="50px" CausesValidation="false">
</asp:CommandField>
</Columns>
protected void BindGV()
{
QualityEntities database = new QualityEntities();
GridView1.DataSource = (from m in database.Machines
from d in database.Workcenters
where m.WorkcenterFK == d.id
select
new { id = m.id, MachineName = m.MachineName, WorkCenterFK = d.WorkCenterName }); ;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) BindGV();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGV();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGV();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
QualityEntities database = new QualityEntities();
BindGV();
Int32 id = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("lblId")).Text);
DropDownList ddl = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlDept"));
TextBox txt = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtMachine"));
Machine mch = (from m in database.Machines where m.id == id select m).Single();
mch.MachineName = txt.Text;
mch.WorkcenterFK = Convert.ToInt32(ddl.SelectedItem.Value);
database.SaveChanges();
GridView1.EditIndex = -1;
BindGV();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
QualityEntities database = new QualityEntities();
DropDownList temp = (DropDownList)(e.Row.FindControl("ddlDept"));
if (temp != null)
{
temp.DataSource = (from w in database.Workcenters select w);
temp.DataTextField = "WorkCenterName";
temp.DataValueField = "id";
temp.DataBind();
Int32 id = Convert.ToInt32(((Label)e.Row.FindControl("lblId")).Text);
}
}
Not sure why the GridView is null, but instead of using a member variable i would use the sender of the event which is always the source of the event (in this case the GridView)
// ...
GridView grid = (GridView)sender;
Int32 id = Convert.ToInt32(((Label)grid.Rows[e.RowIndex].FindControl("lblId")).Text);
// ...

Changing button text of gridview

I have a grid view which contains a button in a template field. I want to change the button text when the button click event is completed. Can somebody send me a sample code.
Thanks in advance
Here is a sample bit of code using the RowCommand() of the GridView.
ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl1" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND" Text="My Text!" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> lst = new List<string>() { "asd", "xxx" };
GridView1.DataSource = lst;
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MYCOMMAND")
{
Button Button1 = (Button)e.CommandSource;
if (Button1 != null)
Button1.Text = "changed text..";
}
}

ASP.NET - Use variable in .aspx page

I'm trying to access a variable or property in my .cs file from the .aspx file but not having any luck. I've looked at several threads on here and have tried them all but still no luck. Here's the scenario; I've got a GridView control with textboxes and a RequiredFieldValidator in one row:
<asp:TemplateField HeaderText="User Name" ItemStyle-Width="10px">
<ItemTemplate>
<asp:Label ID="lblWebLogin" runat="server" Text='<%#Eval("WebLogin") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtWebLogin" runat="server" Text='<%#Eval("WebLogin") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEditWebLogin" runat="server"
ControlToValidate="txtWebLogin" Display="None" ErrorMessage='<%= this.LoginRequired %>'></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtWebLogin" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
There is a ValidationSummary control on the form which is working because I can set the ErrorMessage to a literal string and see that it works.
Here's the code from my .cs:
public string LoginRequired
{
get { return "Error, please try again"; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindDataToGrid();
}
private void BindDataToGrid()
{
DataTable dt;
SqlCommand sc = new SqlCommand();
DAL oDAL = new DAL(DBInformation.Instance.CurrentEncodedConnectionString, DBInformation.Instance.ConnectionTimeout);
//Get User Information.
sc.CommandText = Constants.StoredProcedureNames.GetUsers;
dt = oDAL.SPDataTable(sc, "AllUsers");
gvUsers.DataSource = dt;
foreach (DataRow dr in dt.Rows)
lUser.Add(new User());
gvUsers.DataBind();
}
any ideas as to why it's not working?
Change this
ErrorMessage='<%= this.LoginRequired %>'
in to this
ErrorMessage='<%# this.LoginRequired %>'
and call DataBind() in page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataBind();
BindDataToGrid();
}
}

Find out a CHECKBOX in a DATAGRID in ASP.NET

I have a GRIDVIEW and with several CHECKBOXS.
When i selected a CHECKBOX I need run some code.
To detect it, I use an EVENT HANDLER for the CHECKBOX included in a GRIDVIEW.
I cannot access the CHECKBOX with my wrong code.
Do you have any idea what I am doing wrong? Thanks for your help. Bye
ASPX
<asp:Label ID="uxMessageDisplayer" runat="server" Visible="False" EnableViewState="False"></asp:Label>
<asp:GridView ID="uxUserListDisplayer" runat="server" AutoGenerateColumns="False"
OnRowDataBound="uxUserListDisplayer_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:CheckBox ID="uxActiveCheckBoxSelector" runat="server" AutoPostBack="true" OnCheckedChanged="uxRoleCheckBoxSelector_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Users">
<ItemTemplate>
<asp:Label runat="server" ID="uxUserNameLabelDisplayer" Text='<%# Container.DataItem %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE BEHIND
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Reference the CheckBox that raised this event
//CheckBox uxActiveCheckBoxSelector = sender as CheckBox;
CheckBox activeCheckBox = (CheckBox)FindControl("uxActiveCheckBoxSelector");
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
uxMessageDisplayer.Enabled = false;
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
uxMessageDisplayer.Enabled = false;
}
}
If I am not mistaken by your question, you are trying to set the text of the label on the same row with the checkbox based on its checked status.
Below is the code snippet I tried on my pc, hope it helps.
.aspx:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
//create dummy data
List<string> rows = new List<string>();
Enumerable.Range(1, 5).ToList().ForEach(x => rows.Add(x.ToString()));
//bind dummy data to gridview
GridView1.DataSource = rows;
GridView1.DataBind();
}
protected void CheckBox1_CheckChanged(object sender, EventArgs e)
{
//cast sender to checkbox
CheckBox CheckBox1 = (CheckBox)sender;
//retrieve the row where checkbox is contained
GridViewRow row = (GridViewRow)CheckBox1.NamingContainer;
//find the label in the same row
Label Label1 = (Label)row.FindControl("Label1");
//logics
if (CheckBox1 != null) //make sure checkbox1 is found
{
if (CheckBox1.Checked)
{
if (Label1 != null) //make sure label1 is found
{
Label1.Text = "Checked";
}
}
else
{
if (Label1 != null)
{
Label1.Text = "Unchecked";
}
}
}
}
I'm assuming the event handler is actually registered to the checkbox.
CheckBox activeCheckBox = (CheckBox)sender;
what is "uxActiveCheckBoxSelector" and why are you ignoring sender?
Code corrected as suggest!
Usefull resource for beginners
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Cast sender to CheckBox
CheckBox activeCheckBox = (CheckBox)sender;
// Retrieve the row where CheckBox is contained (NamingContainer used to retrive parent control
GridViewRow row = (GridViewRow)activeCheckBox.NamingContainer;
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
}
}

Categories

Resources