find Countrol inside itemTemplate of Gridview without Gridview Events - c#

i have a Textbox inside ItemTemplate of a Gridview.. i need to find that textbox without using RowDatabound or any other event of Gridview
aspx
<asp:GridView ID="gv_Others" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemTemplate >
<asp:TextBox ID="txtEmp" runat="server" Width=100% Height=22px CssClass="input"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs
protected void Insert_OtherServices()
{
dsJobCardTableAdapters.Select_OtherServiceTableAdapter dsother = new dsJobCardTableAdapters.Select_OtherServiceTableAdapter();
int count = 0;
foreach (GridViewRow row in gv_Others.Rows)
{
//string b = (row.Cells[0].Controls[0] as DataBoundLiteralControl).Text;
//TextBox a = gv_Others.Rows[count].Cells[0].FindControl("txtEmp") as TextBox;
// string test = a.Text;
//TextBox other = (TextBox)gv_Others.Rows[count].FindControl("txtEmp");
TextBox other = (TextBox)gv_Others.TemplateControl.FindControl("txtEmp");
dsother.Insert_OtherService(other.Text);
count++;
}
}
is there any alternative to get the value from textbox which is inside the item template of Gridview

Do you mean that you want to find text box values without looping through GridView rows? If is is the case, jQuery/javascript can be used to achieve this.
Read all text box values on the client-side. You can find more information on how to do this here
Pass these values along with the postback request using a hidden field. Read and use the hidden field value inside your method.

Related

Trying to set value inside a textbox in gridview header

I am trying to set the value of a textbox inside the header template of a grid view but not able to do.
<asp:GridView ID="gv" runat="server"
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="ABC">
<HeaderTemplate><asp:TextBox ID="d1" runat="server">ABC</asp:TextBox></HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs side
trying to set value
gv.HeaderRow.FindControl("d1"). ="DEF"
Expected:textbox with Id="d1" should be set as DEF
Actual:Not getting appropriate syntax to bind it after this code gv.HeaderRow.FindControl("d1").
you can do that by adding onRowDataBound event to your grid and write the following code server side
protected void gridView_RowDataBound(object sender,GridViewRowEventArgs e)
{
TextBox txtd1= (TextBox)e.Row.FindControl("d1");
txtd1.Text="your text";
}
You can set Text of textbox after gridview binded. Below code sets text value of textbox
gv.DataSource = list;
gv.DataBind();
((TextBox)gv.HeaderRow.FindControl("d1")).Text = "DEF";

Retrieve values from GridView by changing a value in a DropDownList

I'm having problems retrieving the current row by changing the status of a DropDownList in the row. My code for the GridView is:
<asp:GridView ID="grdMappingList" runat="server" OnPageIndexChanging="grdMappingList_PageIndexChanging" AutoGenerateColumns="false" AllowPaging="true" PageSize="10" ShowHeaderWhenEmpty="true" UseAccessibleHeader="true" CssClass="table table-hover table-striped segment_list_tbl" >
<PagerStyle CssClass="grid_pagination" HorizontalAlign="Right" VerticalAlign="Middle" BackColor="#DFDFDF" />
<Columns>
<asp:BoundField HeaderText="Mapping Id" DataField="MAPPING_ID"></asp:BoundField>
<asp:BoundField HeaderText="PDM Name" DataField="PDM_NAME"></asp:BoundField>
<asp:BoundField HeaderText="PDM EntityID" DataField="PDM_ENTITY_ID" Visible="false"></asp:BoundField>
<asp:TemplateField HeaderText="Mapping Status" HeaderStyle-CssClass="width_120 aligned_center" ItemStyle-CssClass="width_120 aligned_center" Visible="true">
<ItemTemplate>
<asp:DropDownList id="ddlMappingStatus" runat="server" SelectedValue='<%# Bind("MappingCompleted") %>' OnSelectedIndexChanged="ddlMappingStatus_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="Done" Value="DONE"></asp:ListItem>
<asp:ListItem Text="Not Done" Value="NOT DONE"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code behind is:
protected void ddlMappingStatus_SelectedIndexChanged(object sender, EventArgs e)
{
int MappingID = Convert.ToInt16(grdMappingList.SelectedRow.Cells[0].Text);
DropDownList ddgvOpp = (DropDownList)grdMappingList.SelectedRow.FindControl("ddlMappingStatus");
if (ddgvOpp.Equals("DONE"))
{
}
}
I am getting an error on this line:
DropDownList ddgvOpp (DropDownList)grdMappingList.SelectedRow.FindControl("ddlMappingStatus");
and this line:
int MappingID = Convert.ToInt16(grdMappingList.SelectedRow.Cells[0].Text);
It seems that I can't retrieve the values! I dont know why. When I choose a new status from the DropDownList, I want to get all the values of the row in order to update the record.
Unfortunately, SelectedRow does not mean what you think it means. It doesn't just simply mean the current row you are working on or the current row with the controls that you are using. That property must get set somehow. This is usually done through a "Select" button on the GridView, such as an <asp:ButtonField> with the command name "Select".
You really do not need this however. You just need the row you are working with. Since you are using the SelectedIndexChanged event of your DropDownList, you already have what you need. You just need to go about it a different way.
First, get the DropDownList. Then get the row of the DropDownList. Now do whatever you need with the row.
But, from your code, it looks like you may not even need the row. You just need the value of the DropDownList. So you could skip that all together. But if you do need the row, here is how you would do that too.
protected void ddlMappingStatus_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlMappingStatus = (DropDownList)sender;
if(ddlMappingStatus.SelectedItem.Text.ToUpper() == "DONE")
{
}
GridViewRow row = (GridViewRow)ddlMappingStatus.NamingContainer;
}
Now when you use <asp:BoundField> controls in your GridView, getting their values isn't very clean. You are forced to hardcode the column index like you were doing:
GridViewRow row = (GridViewRow)ddlMappingStatus.NamingContainer;
String mappingID = row.Cells[0].Text;
I tend to prefer using <asp:TemplateField> controls so I can use FindControl() to get what I am after. This prevents any reordering of the columns from breaking the code, as you'd have to hardcode different indexes. So for example, to find that DropDownList (since it already is a <asp:TemplateField>), you'd do something like this:
DropDownList ddlMappingStatus = (DropDownList)row.FindControl("ddlMappingStatus");

How to uncheck the checkbox within the grid view template field?

I have two check boxes with the GridView TemplateField. I want to uncheck the checked boxes after submission. My gridview
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center" DataKeyNames="ShiftID"
Width="177px" onrowdatabound="GridView1_RowDataBound1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChbGrid" runat="server"
oncheckedchanged="ChbGrid_CheckedChanged" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="ChbGridHead" runat="server" AutoPostBack="True"
Font-Bold="True" oncheckedchanged="ChbGridHead_CheckedChanged" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I tried in below mentioned methode
public void checkboxclear()
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkrow = (CheckBox)row.FindControl("ChbGrid");
if(chkrow.Checked==true)
{
chkrow.Checked = false;//it works
}
else
{
CheckBox chkrow1 = (CheckBox)row.FindControl("ChbGridHead");
if (chkrow1.Checked == true)
{
chkrow1.Checked = false;//it shows error like "Object reference not set to instance of an object"
}
}
}
How can I improve my code to solve this issue? Why I am unable to call these check boxes inside the aspx.cs page
You need to check for the RowType becuase your second checkbox is in the HeaderTemplate. For that gridview generates special HeaderRow. That you can directly access and set the value to it.
public void checkboxclear()
{
foreach (GridViewRow row in GridView1.Rows)
{
if(row.RowType == DataControlRowType.DataRow)
{
CheckBox chkrow = (CheckBox)row.FindControl("ChbGrid");
if(chkrow.Checked)
chkrow.Checked = false;
}
}
CheckBox chkrow1 = (CheckBox)GridView1.HeaderRow.FindControl("ChbGridHead");
if (chkrow1.Checked)
chkrow1.Checked = false;
}
Also you don't need to use the chkrow.Checked==true. chkrow.Checked it returns boolean value so that direactly should check in if condition.
I guess I don't know when you are calling this function, but the correct place to pre-set values is in the row databound event.
Having said that the reason your code is blowing up is that you are looking for the header check box in every row, and it is only in the header row. Just access the header through the gridviews header property and do your find control there.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.headerrow(v=vs.110).aspx
Something like
CheckBox chkHeader = (CheckBox)Gridview1.HeaderRow.FindControl("ChbGridHead");

How to add dynamic Texbox in GridView at RunTime?

I would like to add controls like textBox in GridView from code on the fly.
In my project i have one Grid in that i can't decide how many rows and columns are there. so that i just give it DataSource. This working fine.
GridView G = new GridView();
G.DataSourse = dt;
G.DataBind();
now i want to do such thing that in Gridview all the controls are Textbox control so that i can write in that textbox.
TextBox t= new TextBox();
G.Contorls.Add(t);
This will throw exception...
do anyone have any idea about this???
Thanks in advance..
Regards
Amit Vyas
Why not do it in design time with ItemTemplate
<asp:GridView ID="GrdDynamic" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" ID="Name" Text='<%#Eval("Name") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
EDIT
Here is an interesting CodeProject post on dynamically adding template columns
Please check this http://www.devasp.net/net/articles/display/708.html link and use below code:
DropDownList ddl = new DropDownList();
ddl.Visible = true;
ddl.ID = "ddl1";
ddl.Items.Add("Item1");
TableCell cell = new TableCell();
gv.Rows[0].Cells.Add(cell);
gv.Rows[0].Cells[0].Controls.Add(ddl);
If you are looking a way to add TextBox dynamically in the existing GridView, then using RowDataBound event of the GridView would be best solution.
Add a PlaceHolder control in the ItemTemplate field.
<asp:GridView ID="GrdDynamic" runat="server" OnRowDataBound="GridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder runat='server' ID="PlaceHolder1"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
public void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
//find placeholder control
PlaceHolder placeHolder = e.Row.FindControl("PlaceHolder1") as PlaceHolder;
TextBox TextBox1 = new TextBox();
placeHolder.Controls.Add(TextBox1);
}

how to check status of checkboxes in gridview columns on click of button

T have used checkbox column in gridview. On click of a linkbutton, it should be checked that checkboxes in gridview are checked or not. If none check box is checked then it should display alert("Check at leat one check box").
You will have to add some custom Javascript to your page for the client-side alert to show. Here's a method that I've written that works with a GridView called 'GridView1' (this should be the default name if you've just dragged the control onto your ASPX page):
<script type="text/javascript">
function ClientCheck() {
var valid = false;
var gv = document.getElementById("GridView1");
for (var i = 0; i < gv.all.length; i++) {
var node = gv.all[i];
if (node != null && node.type == "checkbox" && node.checked) {
valid = true;
break;
}
}
if (!valid) {
alert("Invalid. Please select a checkbox to continue.");
}
return valid;
}
</script>
You can see that it sets a variable to the GridView control to start with, then iterates through all the children in a for loop. If the child is a checkbox and it is checked, then we set the valid variable to true. If we get to the end of the iteration and no checked checkboxes are found, then valid remains false and we execute the alert.
To link this into your GridView on your ASPX page, first make the button column a TemplateField and surround the LinkButton with your client-side code. If you've used the designer to set up your columns, you can use the "Convert this field into a TemplateField" link in the column editor). Here's an example of the source you'll end up with:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
<Columns>
<asp:TemplateField HeaderText="Button Field" ShowHeader="False">
<ItemTemplate>
<span onclick="return ClientCheck();">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="IDClick" Text='<%# Eval("YourDataSourceItem") %>'></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
// ...your remaining columns...
Using the TemplateField lets us add any client-side code we like. Here we're adding a span and using onclick to call our ClientCheck method.
If you aren't bothered about the alert, you could achieve your aims by using a CustomValidator control, which executes on the server-side.
I hope this helps.
I found the answer. and its working...
function checkBoxselectedornot()
{
var frm=document.forms['aspnetForm'];
var flag=false;
for(var i=0;i<document.forms[0].length;i++)
{
if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)
{
if(document.forms[0].elements[i].checked)
{
flag=true
}
}
}
if (flag==true)
{
return true
}else
{
alert('Please select at least one Event.')
return false
}
}
and girdview code is...
<asp:BoundField ItemStyle-Width ="100px" DataField ="EventStartDate" DataFormatString ="{0:g}" HeaderText ="<%$ Resources:stringsRes, ctl_EventList_StartDate %>" SortExpression ="EventStartDate" HtmlEncode ="true" ItemStyle-Wrap ="false" />
<asp:BoundField ItemStyle-Width="100px" DataField="EventDate" DataFormatString="{0:g}" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Date %>" SortExpression="EventDate" HtmlEncode="true" ItemStyle-Wrap="false" />
<asp:ButtonField ItemStyle-Width="150px" ButtonType="Link" DataTextField="EventName" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Event %>" SortExpression="EventName" CommandName="show_details" CausesValidation="false" />
<asp:BoundField DataField="EventLocation" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Location %>" SortExpression="EventLocation" />
<asp:TemplateField HeaderText ="Select">
<ItemTemplate >
<asp:CheckBox ID="chkDownloadSelectedEvent" runat ="server" AutoPostBack ="false" Onclick="eachCheck();"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle Height="25px" />
<HeaderStyle Height="30px"/>
</asp:GridView>
and there is a link button ....
I havnt used the checkbox in grid view but would you not do a for loop around the columns in gridview and check the state? Myabe add a count and if 0 then alert.
var grid = document.getElementById("gridId"); //Retrieve the grid
var inputs = grid.getElementsByTagName("input"); //Retrieve all the input elements from the grid
var isValid = false;
for (var i=0; i < inputs.length; i += 1) { //Iterate over every input element retrieved
if (inputs[i].type === "checkbox") { //If the current element's type is checkbox, then it is wat we need
if(inputs[i].checked === true) { //If the current checkbox is true, then atleast one checkbox is ticked, so break the loop
isValid = true;
break;
}
}
}
if(!isValid) {
alert('Check at least one checkbox');
}

Categories