Asp.net - Changing Textbox field into label in gridview at code behind - c#

<ItemTemplate>
<asp:TextBox ID="Q1" runat="server" Text='<%# Bind("Q1") %>'></asp:TextBox>
</ItemTemplate>
.
.
.
<ItemTemplate>
<asp:TextBox ID="Q2" runat="server" Text='<%# Bind("Q2") %>'></asp:TextBox>
</ItemTemplate>
I currently have a page with fields as textbox and I would like to change some of them label based on condition in code behind.
For example if Window_name='Q2' --> make Q2 Q3 Q4 textbox and Q1 label
if it is Window_name='Q3' make Q3 and Q4 textbox but Q1 and Q2 label
Btw, I'm not using edit/select gridview modes as I made it bulk update gridview (one button to update all rows)

I'm trying to help you with a sample of two controls and sample grid view ID 'GridView1' here, alter it according to your code:
You could either have the labels created instead of showing the text box in the CODE BEHIND or create both textboxes and labels initially and show them when needed.
Also instead of doing it in the Page_Load function you could do it in the 'RowDataBound' event of GridView and bind the GridView each every time a post back is done.
ASPX Code:
<ItemTemplate>
<asp:TextBox ID="Q1" runat="server" Text='<%# Bind("Q1") %>'></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Q1") %>' Visible="false">
</asp:Label>
</ItemTemplate>
.....
<ItemTemplate>
<asp:TextBox ID="Q2" runat="server" Text='<%# Bind("Q2") %>'></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Q2") %>' Visible="false">
</asp:Label>
</ItemTemplate>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
//Bind your grid view
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int rowIndex = e.Row.RowIndex;
//First fetch your textboxes and labeles
TextBox textBoxQ1 = GridView1.Rows[rowIndex].FindControl("Q1") as TextBox;
TextBox textBoxQ2 = GridView1.Rows[rowIndex].FindControl("Q2") as TextBox;
Label Label1 = GridView1.Rows[rowIndex].FindControl("Label1") as Label;
Label Label2 = GridView1.Rows[rowIndex].FindControl("Label2") as Label;
if (Window_name.Equals("Q2"))
{
//Set 'visiblity' to 'true' for those LABEL you want to show. Sample one below
Label2.Visible = false;
//Set 'visibilty' to 'false' for those TEXT BOXES you want to hide. Sample one below
textBoxQ2.Visible = false;
}
}
Let me know in case of any queries.

Related

Get Column value 'TemplateField' of Each row in Button Click event

I have created a gridview using TemplateField. And Added Add Button And this redirects to other page and i want to get the one column value of row.
Here is the code -
<Columns>
<asp:TemplateField HeaderText="Accession ID">
<ItemTemplate>
<asp:Label Text='<%# Eval("AccessionID") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" Text="Hello" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFirstNameFooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
......
<asp:TemplateField HeaderText="Add Container">
<ItemTemplate>
<asp:Button ID="btnAddContainer" runat="server" CommandName="" Text="Add Container" CommandArgument='<%# Eval("AccessionID") %>' OnClick="ContainerforAccession" class="btn btn-primary btn-md" />
</ItemTemplate>
</asp:TemplateField>
CS Code -
protected void ContainerforAccession(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
}
I have this code with me. I want to get first column value (AccessionID) in my case in every button click of the Grid.
I have tried across multiple solutions. But unfortunately, we have the answers for 'asp:BoundField' Implementation. I am looking for 'asp:TemplateField'
Please let me know if i need to convert to asp:BoundField. If so, How can the above design can be changed - Binding Text='<%# Eval("AccessionID") %> to Textbox.
Thanks in advance. Looking for a solution.
Change the OnClick of the button to OnCommand. Then you have access to the CommandEventArgs.
<asp:Button ID="btnAddContainer" OnCommand="ContainerforAccession"
protected void ContainerforAccession(object sender, CommandEventArgs e)
{
string AccessionID = e.CommandArgument.ToString();
}
Changed All the Template fields to Bound-Fields and in cs code -
int AccessionID = Int32.Parse((sender as Button).CommandArgument);
Solved my issue !

How to update GridView from TextBox in ItemTemplate with List DataSource

I'm stuck and have no idea what to do, can you help me please?
I have this grid in page markup
<asp:GridView ID="gridEmployees" runat="server"
AllowPaging="True"
AllowSorting="<%# AllowSorting %>"
OnPageIndexChanging="grdView_PageIndexChanging"
OnSorting="gridEmployees_Sorting"
OnRowEditing="gridEmployees_RowEditing"
OnRowUpdating="gridEmployees_RowUpdating"
OnRowCancelingEdit="gridEmployees_RowCancelingEdit"
OnRowUpdated="gridEmployees_RowUpdated"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Full name" SortExpression="FullName">
<ItemTemplate>
<asp:Label runat="server" ID="lbSalary" Width="200px" Text='<%# Eval("FullName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary" SortExpression="Salary">
<%--http://www.codeproject.com/Articles/23471/Editable-GridView-in-ASP-NET--%>
<ItemTemplate >
<div >
<asp:TextBox Width="100px" OnTextChanged="tbSalary_TextChanged" AutoPostBack="True" style="text-align: right" TextMode="SingleLine" runat="server" ID="tbSalary" Text='<%# Bind("Salary", "{0:c0}") %>'></asp:TextBox>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I want two columns - label (name) and textBox (salary). When user edits TextBox - data have to be updated automatically.
My CodeBehind looks like:
private static readonly DbManager DbManager = new DbManager();
private int selectedJobId = 1; // TODO:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ddlJobs.DataTextField = "name";
ddlJobs.DataValueField = "id";
ddlJobs.DataSource = DbManager.GetJobs();
ddlJobs.SelectedValue = selectedJobId.ToString();
ddlJobs.DataBind();
ddlJobs.DataBound += (o, args) =>
{
selectedJobId = Convert.ToInt32(ddlJobs.SelectedValue);
FillTable();
};
}
else
{
selectedJobId = Convert.ToInt32(ddlJobs.SelectedValue);
}
Page.DataBind();
}
protected void FillTable()
{
gridEmployees.DataSource = GetEmployees(); // List<Employees>
gridEmployees.DataBind();
}
I thought that row will raise Updated event when I update TextBox, but, unfortunately, it doesnt, probaly it's 'cause grid is not in editMode. So, I just made workaround - if TB edited - raise event and process it.
Well, now page is reloading with IsPostback = false, but no event is raised, not WebGrid's not TB's.
I've found some clue here, but my source is not SqlDataSource. What's wrong with my code, source? How to update row when TB changed in my case.
Just go through this artical .You will be able to fire textchange event from textbox inside the gridview
[http://www.codeproject.com/Tips/663684/Fire-TextBox-TextChanged-Event-from-GridView][1]

How to pass an Eval method through the attributes.add property?

I have a Gridview with all the rows as textboxes and one edit button in the last column. All the textboxes have an onclick property which calls a javascript method. Here is the HTML code of one of the textbox:
<asp:TextBox ID="txtLoginName" Onclick='<%# "pass(" + Eval("userid") + ");" %>'
Text='<%# Eval("LoginName")%>' runat="server"></asp:TextBox>
When a user clicks on the Edit button, the onclick property is removed and the button changes to Save. After making the changes, when a user clicks Save, I want to re-add the onclick property again. This is the code I have tried:
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
TextBox lstTxt = (TextBox)row.FindControl("txtLoginName");
if (btn.Text == "Edit")
{
lstTxt.Attributes.Remove("onclick");
btn.Text = "Save";
}
else
{
lstTxt.Attributes.Add("onclick", "<%# 'pass(" + Eval("userid") + ");' %>");
btn.Text = "Edit";
}
But its showing error
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control
How to pass that correctly?
You have to get the userid from sonmewhere else. You could store it for example in a HiddenField or invisible label and use e.Row.FindControl to get this control. Another approach is using the button's CommandArgument.
aspx:
<asp:Button ID="btnEdit" runat="server" CommandName="Edit" CommandArgument='<%# Eval("userid") %>'>
codebehind:
string userID = btn.CommandArgument.ToString();
lstTxt.Attributes.Add("onclick", "pass(" + userID + ");");
Here is the approach with a control like HiddenField:
<asp:TemplateField HeaderText="UserID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="HidUserID" Value='<%#Eval("userid") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
Now you can get it from codebehind via FindControl:
HiddenField hidUserID = (HiddenField)e.Row.FindControl("HidUserID");
string userID = hidUserID.Value;
You can use like this:
use it in grid view template field
<asp:TemplateField HeaderText="userid" Visible="false">
<ItemTemplate>
<asp:Label runat="server" id="lblUserid" style="display:none" Text='<%# Eval("UserID") %>' />
</ItemTemplate>
</asp:TemplateField>
find in code behind
GridViewRow row = (GridViewRow)btn.NamingContainer;
Label lbl = (TextBox)row.FindControl("lblUserid");
string userid=lblUserid.Text;
lstTxt.Attributes.Add("onclick", "<%# 'pass(" + userid + ");' %>");

C# getting selected value from dropdownlist in gridview asp net

How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?
On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.
The code is below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText="Entry">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duty">
<ItemTemplate>
<asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind is below.
protected void ddl1_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
Duty dy = new Duty();
dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "dutyid";
ddl.DataValueField = "dutyid";
ddl.DataBind();
TextBox1.Text = ddl.SelectedValue;
}
}
You need to use SelectedIndexChanged handler to show selected value:
Markup:
<asp:DropDownList ID="duty" runat="server" OnLoad="ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged"></asp:DropDownList>
Code-behind:
protected void duty_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
DropDownList duty= (DropDownList) gvr.FindControl("duty");
TextBox1.Text = duty.SelectedItem.Value;
}
I had a similar problem using the DropDownLists in GridView. My solution was to adjust the onLoad for the dropdown so that it wouldn't re-write the DropDownList on every post back. This way if there's something there then it won't re-populate it.
protected void dropDownLoad(object sender, EventArgs e)
{
DropDownList dropDown = sender as DropDownList;
if (dropDown.SelectedValue == null || dropDown.SelectedValue == "")
{
// Your Code to populate table
}
}
You should look into using data binding instead. You can bind the textbox.Text to the selecteditem.value, this will ensure that proper updating takes place
this happens to me once then i code like this... but i didnt use the onLoad attribute, tell me if this works,
<asp:TemplateField HeaderText="duty" SortExpression="duty">
<EditItemTemplate>
<asp:TextBox ID="duty" runat="server" Text='<%# Bind("duty_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblduty" runat="server" Text='<%# Eval("duty_Name") %>' />
<asp:DropDownList ID="ddlduty" runat="server" CssClass="dropdownlist"
OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" Visible = "false"
>
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle Width="5%" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

Get the value of columns on Check_changed Event of checkbox in gridview

I have a grid view which contains date and time string in dataBound field and check box in item template field. Now when user check any check box, i want to make isChecked field of my data table(Which is data source for gridview and isCheck is added programatically) true/false accourdingly. How can I get date time string from gridview based on the check box checked/uncheked??
You can do like...
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" Text='<%# Eval("Date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Checkbox">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true"
oncheckedchanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
String Date = ((Label)((CheckBox)sender).Parent.FindControl("lblDate")).Text;
}

Categories

Resources