ASP.NET - Use variable in .aspx page - c#

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();
}
}

Related

Add Event on specific control in the gridview

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

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);
// ...

How to get the Command Argument on Row Data bound Event of gridview

i am binding the values to gridview like this
<asp:GridView ID="grdViewAttachment_Client" runat="server" Width="615px" AutoGenerateColumns="False" GridLines="None" CssClass="grid-view" OnRowCommand="grdViewAttachment_Client_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Attachment" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnAttachments" runat="server" Text="Delete" CommandName="Delete" CommandArgument='<%#Eval("AttachmentId") %>' ></asp:LinkButton>
</ItemTemplate>
<HeaderStyle/>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attachment" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<%--<asp:LinkButton ID="lnkbtnAttachments" runat="server" Text='<%#Eval("AttachmentName") %>' CommandName='<%#Eval("AttachmentName")%>' CommandArgument='<%#Eval("AttachmentId") %>'></asp:LinkButton>--%>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("AttachmentName") %>' CommandName='<%#Eval("AttachmentName")%>' ></asp:LinkButton>
</ItemTemplate>
<HeaderStyle/>
</asp:TemplateField>
<asp:TemplateField HeaderText="AssignedTo" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<asp:Label ID="lblAssignedTo" Text='<%#Eval("AssignedTo") %>' runat="server" CssClass="body-text"></asp:Label>
</ItemTemplate>
<HeaderStyle />
</asp:TemplateField>
<asp:TemplateField HeaderText="CreationDate" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<asp:Label ID="lblCreationDate" Text='<%#Eval("CreationDate") %>' runat="server" CssClass="body-text"></asp:Label>
</ItemTemplate>
<HeaderStyle />
</asp:TemplateField>
</Columns>
</asp:GridView>
In my row command event i write as follows code
protected void grdViewAttachment_Client_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection m_Conn = new SqlConnection(Utilities.ConnectionString());
SqlCommand m_oCmd;
int iStID = int.Parse(e.CommandArgument.ToString());
int pk = 0;
int.TryParse(e.CommandArgument as string, out pk);
string strStoreProcName = null;
DataSet oDS1 = new DataSet();
if (e.CommandName == "Delete")
{
strStoreProcName = StoredProcNames.Attachments_uspDeleteAttachs;
m_oCmd = new SqlCommand(strStoreProcName, m_Conn);
m_oCmd.CommandType = CommandType.StoredProcedure;
m_oCmd.Parameters.Add("#AttachmentId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument.ToString());
m_Conn.Open();
m_oCmd.ExecuteNonQuery();
AttachmentDetails();
}
string fname = e.CommandName.ToString();
}
But i am not getting the value i am getting the exception as Input string was not in correct format can any one help me
es #Muhammad Akhtar was right .It should be like
int iStID = Convert.ToInt32(gridName.DataKeys[Convert.ToInt32(e.CommandArgument.ToString())].Value);
Specify Datakey property in your data grid . and you can access the data key value of the current row as above
add datakey name to your statement
ID_COLUMN should be a column from data table which you are binding to gridview
Write this code for row Created
protected void grdViewAttachment_Client_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkbtnAttachments=(LinkButton)e.Row.FindControl("lnkbtnAttachments");
lnkbtnAttachments.CommandArgument = e.Row.RowIndex.ToString();
// similarly write for other controls
}
}
Do not use Delete standard commandName otherwise you have to handle the "RowDeleting" event.
Take a look at this sample:
.aspx markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
Data :
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:LinkButton ID="btnDelete" runat="server"
CommandArgument='<%# Eval("No") %>' CommandName="Del">Delete</asp:LinkButton>
<asp:LinkButton ID="btnShow" runat="server" CommandArgument='<%# Eval("No") %>'
CommandName="Show">Show</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
public class Data
{
public int No { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Data> list = new List<Data>()
{
new Data(){ No=1, Name="A"},
new Data(){ No=2, Name="B"},
new Data(){ No=3, Name="C"}
};
GridView1.DataSource = list;
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del")
{
Response.Write("Delete : " + e.CommandArgument);
}
else
if (e.CommandName == "Show")
{
Response.Write("Show : " + e.CommandArgument);
}
}
As you are not passing command Argument this will always give null reference . Try this in your control where ever you required.
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("AttachmentName") %>' CommandName='<%#Eval("AttachmentName")%>' CommandArgument='<%#Eval("AttachmentId") %>'>
<ItemTemplate>
<asp:LinkButton ID="lnkDetails" runat="server" CommandName="Details" CommandArgument='<%#Eval("ID")%>'
ToolTip="View Details">View</asp:LinkButton>
</ItemTemplate>
protected void gvmain_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Details")
{
int id = Convert.ToInt32(e.CommandArgument);
Response.Redirect("~/MEMBER/UploadedDocList.aspx?id=" + id, false);
}
}

C# Question About Delete Data Grid

I have binded a data grid to an array. Also, there is a button there to delete the row. The problem is that I am not sure how to implement it since the data source is an array.
See below
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:Label ID="lblItems" runat="server" Text='<%# Container.DataItem>' />
</ItemTemplate>
</asp:TemplateColumn>
<asp:ButtonColumn ButtonType="PushButton" CommandName="Delete" Text="Delete">
</asp:ButtonColumn>
</Columns>
and here I would like to implement it..
private void DataGrid1_DeleteCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
int rowToDelete = e.Item.ItemIndex;
myDataGrid.DataBind();
}
In the code for the deletion, how can I access the index of my array based on the button clicked (per row)?
Here is an example
Markup.
<asp:DataGrid ID="DataGrid1" runat="server"
AutoGenerateColumns="False"
OnDeleteCommand="DataGrid1_DeleteCommand">
<Columns>
<asp:TemplateColumn HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblItems" runat="server"
Text='<%# Container.DataItem %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:ButtonColumn ButtonType="PushButton"
CommandName="Delete"
HeaderText="Actions"
Text="Delete">
</asp:ButtonColumn>
</Columns>
</asp:DataGrid>
Code-behind.
private static string[] names = new string[] { "Matt", "Joanne", "Robert" };
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataGrid1.DataSource = names;
DataGrid1.DataBind();
}
protected void DataGrid1_DeleteCommand(object source, DataGridCommandEventArgs e)
{
string deletedItem = ((Label) DataGrid1.Items[e.Item.ItemIndex].FindControl("lblItems")).Text;
names = names.Where(val => val != deletedItem).ToArray();
BindGrid();
}
Hope this helps.
Have you tried to access your src object using the method below (notice this is 'RowDeleting' event on gridview)?
protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
MyObject o = (MyObject)gv.Rows[e.RowIndex].DataItem;
}
There are also other tricks like storing an id in a hiddenfield on the row and then on the delete command you search for the control and pluck your value. My preference is the method above but really depends on what your goal is.
protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
HiddenField field = (HiddenField)gv.Rows[e.RowIndex].FindControl("myHiddenField");
string myValue = field.Value;
// delete it and rebind
}

In a GridView, how to add multiple commands to one item template?

I stripped this example to make it simple. I have a gridview with a template field. The template field contains two buttons and a label (They must be in the same template field). I want the first button to set the label text to "Win", and the other button to set the label text to "fail". The onrowcommand doesnt seem to be triggered by buttons in a template field. How can I accomplish this?
My gridview code is below:
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True" AutoGenerateColumns="False"
OnRowCommand="Gridview1_RowCommand">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnWin" runat="server" CommandName="Win" Text="Win" />
<asp:Button ID="btnFail" runat="server" CommandName="Fail" Text="Fail" />
<asp:Label ID="lblStatus" runat="server" Text='<%# Bind("text") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and my code behind:
protected void Page_Load(object sender, EventArgs e)
{
DataTable myTable = new DataTable();
myTable.Columns.Add("text", typeof(string));
myTable.Rows.Add("First Entry");
myTable.Rows.Add("Second Entry");
GridView1.DataSource = myTable;
GridView1.DataBind();
}
public void Gridview1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
//set lblStatus.text to "Win", or "Fail"
}
Thanks in advance!
Here you go...
public void Gridview1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
lblStatus.Text = e.CommandName;
}
I see that there is more to this question than is answered here, bear with me. One way would be to delegate the OnCommand event of each button to its designated event handler, as follows:
<div>
<asp:GridView ID="MyGridView" runat="server" EnableModelValidation="true" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="MyWinButton" runat="server" OnCommand="MyWinButton_OnCommand" CommandName="Win" Text="Win" />
<asp:Label ID="MyStatusLabel" runat="server" Text='<%# Bind("text") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
public void MyWinButton_OnCommand(Object sender, CommandEventArgs e)
{
var label = ((Button)sender).Parent.FindControl("MyStatusLabel") as Label;
label.Text = e.CommandName;
}
Also, as Alison suggests, you won't see the desired output of this unless you use !IsPostBack in Page_Load. Furthermore, on doing so this does in fact enable you to use the one row command event handler as initially suggested, albeit with a slight change in the label retrieval:
public void MyGridView_OnRowCommand(Object sender, GridViewCommandEventArgs e)
{
var label = ((Button)e.CommandSource).Parent.FindControl("MyStatusLabel") as Label;
label.Text = e.CommandName;
}
Are you using a MasterPage with ViewState turned off? Buttons in a template field with ViewState set to false will not fire.
Also, you should change your Page_Load to NOT rebind on postback"
protected void Page_Load(object sender, EventArgs e)
{
if (!page.IsPostBack) {
DataTable myTable = new DataTable();
myTable.Columns.Add("text", typeof(string));
myTable.Rows.Add("First Entry");
myTable.Rows.Add("Second Entry");
GridView1.DataSource = myTable;
GridView1.DataBind();
}
}
The rebinding may be interfering.

Categories

Resources