Let me get this straight. I manage to create a custom Gridview with a single checkbox but my problem here is that I want to include multiple dynamic Checkbox.
Here is my code:
<%# Control Language="C#" AutoEventWireup="true" EnableTheming="true" CodeFile="GridviewControl.ascx.cs" Inherits="UserControl_GridviewControl" %>
<link href="../Template/CSS/Style.css"type="text/css" rel="Stylesheet" />
<div>
<span id="Span5" style="font-family: Arial; font-size:12px;" ><asp:Label ID="lblCount" runat="server" Text="0" Font-Bold="true"></asp:Label>
Record/s</span>
<span class="maintenance-btns">
<asp:Button ID="btnNew" runat="server" Text=" New " onclick="btnNew_Click"/>
<asp:Button ID="btnDel" runat="server" Text=" Delete " onclick="btnDel_Click"/>
</span>
</div>
<asp:Panel ID="pnlPc" runat="server" CssClass="div-grid" ScrollBars="Auto">
<asp:GridView ID="gvListing" runat="server" AllowPaging="True" AutoGenerateSelectButton="true"
OnRowDataBound="gvListing_RowDataBound" skinid="gvListing"
onselectedindexchanged="gvListing_SelectedIndexChanged"
onpageindexchanging="gvListing_PageIndexChanging" PageSize="50" >
<FooterStyle CssClass="grid-footer" />
<Columns>
<asp:TemplateField HeaderText="CheckAll">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" AutoPostBack="true"
OnCheckedChanged="chkSelectAll_CheckedChanged" CssClass="select-all"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true"
OnCheckedChanged="chkSelect_CheckedChanged" CssClass="listing-checkbox"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
In this gridview I only have a checkboxes at the first column. I want to put the dynamically generated checkboxes at the last column.
P.S.: How do I retrieve the id with those dynamically create checkboxes?
You can do like this
protected void gvData_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow objRow in gvData.Rows)
{
TableCell tcCheckCell = new TableCell();
var checkBox = new CheckBox();
checkBox.CheckedChanged += checkBox_CheckedChanged;
tcCheckCell.Controls.Add(checkBox);
objRow.Cells.AddAt(0, tcCheckCell);
}
}
void checkBox_CheckedChanged(object sender, EventArgs e)
{
//do something
}
Related
I am having a gridview in asp.net, and in the table I have two columns.
Now I must show the column index value row by row on the button click in form of a alert for dllDesc and txtBoxDesc fields.
<asp:GridView ID="gvCar" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataKeyNames="LevelID" OnRowDataBound="gvCar_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Car">
<ItemTemplate>
<asp:Label ID="Car" runat="server" Width="150px" Height="30px" Font-Names="Georgia" MyCustomAttr="foo" margin-Left="100px" Text='<%# Bind("CharName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:DropDownList ID="ddlDesc" Width="142px" Height="35px" Font-Names="Georgia" margin-Left="100px" runat="server">
</asp:DropDownList>
<asp:TextBox ID="txtBoxDesc" runat="server" Width="130px" Height="28px" Font-Names="Georgia" margin-Left="100px" Text=''></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
I managed to get the value for rows(code below) but i could not find a way to show it for columns.
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvCar.Rows)
{
string PrimaryKey = gvCar.DataKeys[gvr.RowIndex].Values[0].ToString();
MessageBox.Show(PrimaryKey);
}
}
Can someone help me please?
just bind it like this on grid view don't need to do anything else
<asp:TemplateField HeaderText="No.">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
EDIT UPDATE 2
just add on selected index Changed event
<asp:GridView ID="gvCar" runat="server" OnSelectedIndexChanged="gvCar_SelectedIndexChanged">
and in your cs file
protected void gvCar_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string a = gvCar.SelectedRow.Cells[0].Text; //Write here that cell index of index no
}
catch (Exception ex)
{
}
}
if you want to do that by row command then open bellow link
Row command example
that will work for you
You just iterate over the columns and then you ask for the header text:`
for (int i = 0; i < gvCar.Columns.Count; i++)
{
string columnHeader = gvCar.Columns[i].HeaderText;
}
EDITED AFTER FEEDBACK:
For the datatables I think it works like this:
for (int i = 0; i < dt.Columns.Count; i++)
{
int colIndex = dt.Columns[i].Ordinal;
}
Hope this helps!
I have a GridView with a TemplateField. Inside the ItemTemplate there are 2 TextBox's and then a <table> with an Panel. In that Panel there's another TextBox.
How do I get the value of that last TextBox?
I have the index of the gridview's row, but I don't know how to get on from there.
(Data from DB is bound at page load).
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:GridView ID="grv_Four_Rows" runat="server" AutoGenerateColumns="False"
ShowHeader="False" CellPadding="3" CssClass="myGrid" DataKeyNames="Test1_First_Name">
<RowStyle BackColor="#b5c7de" />
<AlternatingRowStyle BackColor="#d1e0e0" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txbFirstName" runat="server" CssClass="myTextBox" ReadOnly="false" Text='<%# Eval("Test1_First_Name")%>'></asp:TextBox>
<asp:TextBox ID="txbLastName" runat="server" CssClass="myTextBox" ReadOnly="true" Text='<%# Eval("Test1_Last_Name")%>'></asp:TextBox>
<table style="width: 350px;">
<asp:Panel ID="upp_2nd_row" runat="server" Visible="true">
<td style="float: left">
<a style="color: red; font-weight: bold;">Address: </a>
<asp:TextBox ID="txbAddress" Width="200px" Font-Bold="true" runat="server" Text='<%# Eval("Test1_Address")%>' />
</td>
<td style="float: right">
<asp:Button ID="btn_Edit_Details" runat="server" Text="Go" Font-Bold="true"
OnClick="my_Update_details" CommandArgument='<%#DataBinder.Eval(Container, "DataItemIndex")%>' />
</td>
</asp:Panel>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Label ID="lblMessage1" runat="server" BackColor="Yellow" Font-Bold="true"></asp:Label>
C# Code behind:
protected void my_Update_details(object sender, EventArgs e)
{
string my_row_index = (sender as Button).CommandArgument;
lblMessage1.Text = "Row Index: " + my_row_index;
}
When I click the "Go" button in any row, the my_Update_details event is fired. All it does is, it displays the gridview's current row's index, and the value is correct.
But in the my_Update_details I also want to pick the values of the textbox's, and that's where I'm stuck (user is supposed to change their values and the 'Go' button should update the DB). In the following example I clicked the button in the 4th row and it correctly displays the index as 3 :
So this is how it works: first I rack my brains for a couple of days, then I post a question in SO, then - after 2 minutes I find a solution...
All I did was add a line in the my_Update_details method (the second line) :
protected void my_Update_details(object sender, EventArgs e)
{
string my_row_index = (sender as Button).CommandArgument;
TextBox AAAAAA = (TextBox)grv_Four_Rows.Rows[Convert.ToInt32(my_row_index)].Cells[0].FindControl("txbAddress");
lblMessage1.Text = "Address: " + AAAAAA.Text;
lblMessage2.Text = "Row Index: " + my_row_index;
}
and now I get:
which is exctly what I needed : to get the value that's in the txbAddress textbox.
Hope it will help someone in the future....
I am trying to get the value of textbox "Qty" inside a datalist. It does not work. What is wrong? I have both the CartItem label and the datelist inside the ajax updatepanel. Thanks for any help. Here is my code:
<asp:Label ID="CartItems" runat="server" Text="CartItem"></asp:Label>
<br />
<asp:DataList ID="DataList1" runat="server" CellPadding="10"
DataKeyField="product_id" DataSourceID="SqlDataSource1" RepeatColumns="2">
<ItemTemplate>
<asp:Label ID="product_id" runat="server"
Text='<%# Eval("product_id") %>' /><br/>
<asp:Label ID="product_name" runat="server"
Text='<%# Eval("product_name") %>' />
<br />
Qty
<br/>
<asp:TextBox ID="Qty" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to Cart"
onClick="ButtonAddToCart_Click"/>
<br />
</ItemTemplate>
</asp:DataList>
and here is the button click event. The CartItem has null value:
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
CartItem.Text = DataList1.FindControl("Qty").ToString();
}
TextBox Qty = (TextBox)DataList1.FindControl("Qty");
if(Qty != null)
{
CartItem.Text =Qty.Text;
}
You can use NamingContainer or Parent to access sibling controls
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
var button = sender as Button;
var textbox = button.NamingContainer.FindControl("Qty") as TextBox;
CartItem.Text = textbox.Text;
}
I prefer you to use item_command event of the datalist
do some think like this.
<asp:Label ID="CartItems" runat="server" Text="CartItem"></asp:Label>
<br />
<asp:DataList ID="DataList1" runat="server" CellPadding="10" DataKeyField="product_id" DataSourceID="SqlDataSource1" RepeatColumns="2">
<ItemTemplate>
<asp:Label ID="product_id" runat="server"
Text='<%# Eval("product_id") %>' /><br/>
<asp:Label ID="product_name" runat="server"
Text='<%# Eval("product_name") %>' />
<br />
Qty
<br/>
<asp:TextBox ID="Qty" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to Cart" CommandName="addtocart2" OnCommand="DataList1_ItemCommand"
/>
<br />
</ItemTemplate>
</asp:DataList>
Here is the item_command event that works.
public void DataList1_ItemCommand(object source, System.Web.UI.WebControls.CommandEventArgs e){
TextBox qtytxtbox = DataList1.FindControl("Qty") as TextBox;
}
You can do like this
protected void ButtonAddToCart_Click(object sender, EventArgs e)
{
Button ButtonAddToCart= (Button)sender;
DataListItem item = (DataListItem)ButtonAddToCart.NamingContainer;
var textbox = (TextBox)item.FindControl("Qty");
}
try this one
TextBox txtquantity = (TextBox)(e.Item.FindControl("Qty"));
simply use this......You will get the value in txtquantity
In my page i have a CheckBoxList control and i would like all the checkboxes to be checked by default. how can i do that? i have tried couple ways but it is not doing it. here is my code behind:
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach(GridViewRow gr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("chkItem");
cb.Checked = true;
if(((CheckBox)sender).Checked)
cb.Checked = true;
else
cb.Checked = false;
}
}
and here is my ASPX code:
<asp:TemplateField HeaderText="Check All">
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" AutoPostBack="True" OnCheckedChanged="chkAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkItem" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Use the following ASPX:
<asp:GridView runat="server" ID="m_gridView" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Check All">
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" AutoPostBack="True" OnCheckedChanged="chkAll_CheckedChanged" Checked="True" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkItem" runat="server" Checked="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
It should have Check All and the individual check boxes checked by default.
In you code behind do the following:
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox l_cbAll = (CheckBox)m_gridView.HeaderRow.FindControl("chkAll");
foreach (GridViewRow l_row in m_gridView.Rows)
{
CheckBox l_cb = (CheckBox)l_row.FindControl("chkItem");
l_cb.Checked = l_cbAll.Checked;
}
}
I am using AjaxToolKit and have created a gridview with Details button. I want to open a panel that will have 2 more gridviews upon Details button click as ModalPopupExtender. It should also highlight the row which is being edited.
I am getting this error...
Webpage error details
Message: Invalid character
Line: 269
Char: 7
Code: 0
URI: http://localhost:5427/ModalPopUpInGridView/Default3.aspx
I checked both the design/source as well as the code but I couldn't find any invalid characters. Also when I click on the Details buttons at runtime the gridview disappears.
Any suggestions?
Here is the complete source code:
HTML Part:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<style>
.modalBackground
{
background-color:Gray;
filter:alpha(opacity=70);
opacity:0.7;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager ID="scriptManager" runat="server" />
<div>
<p style="background-color:AliceBlue; width:95%">
Example of using a
ModalPopupExtender to edit the indivdual rows of a GridView.<br />
To test out the functionality,
click the Details button of any of the rows and watch what happens.<br />
</p>
<br />
<asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblTitle" runat="server" Text="Customers" BackColor="lightblue" Width="95%" />
<asp:GridView
ID="gvCustomers" runat="server"
AutoGenerateColumns="false"
AllowPaging="true" AllowSorting="true"
PageSize=10 OnPageIndexChanging="myGridView_PageIndexChanging"
OnRowDataBound="Gridview_RowDataBound" EnableViewState="false"
Width="95%">
<AlternatingRowStyle BackColor="AliceBlue"
/>
<HeaderStyle HorizontalAlign="Left"
/>
<Columns>
<asp:TemplateField HeaderText="V">
<ItemTemplate>
<asp:CheckBox ID="chkVerified" runat="server"
Checked='<%# Eval("V") == "True" ? true : false %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NT">
<ItemTemplate>
<asp:CheckBox ID="chkDeleted" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="P">
<ItemTemplate >
<asp:Label ID="P" runat="server" Text='<%# Eval("P") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FN">
<ItemTemplate >
<asp:Label ID="FN" runat="server" Text='<%# Eval("FN") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="MN" >
<ItemTemplate >
<asp:Label ID="MN" runat="server" Text='<%# Eval("MN") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LN" >
<ItemTemplate >
<asp:Label ID="LN" runat="server" Text='<%# Eval("LN") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate >
<asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnViewDetails"
runat="server"
Text="Details"
OnClick="btnViewDetails_Click"
/>
</ItemTemplate>
<ControlStyle Width="50px" />
<HeaderStyle Width="60px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button id="btnShowPopup" runat="server" style="display:none" />
<ajaxToolKit:ModalPopupExtender
ID="mdlPopup" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlPopup"
CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px" style="display:none">
<asp:UpdatePanel ID="updPnlCustomerDetail" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblCustomerDetail" runat="server"
Text="Customer
Detail" BackColor="lightblue" Width="95%" />
<asp:Panel ID="pnlPopupInner" runat="server">
<table>
<tr><td>Test1</td></tr>
<tr><td>Test2</td></tr>
<tr><td>Test3</td></tr>
</table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<div align="right" style="width:95%">
<asp:Button
ID="btnSave" runat="server"
Text="Save"
OnClientClick="alert(’Sorry, but I didnt implement save because I
dont want my northwind database getting messed up.’); return false;"
Width="50px" />
<asp:Button ID="btnClose" runat="server" Text="Close" Width="50px" />
</div>
</asp:Panel>
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Drawing;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MDRTeachersTest; //Webservice
public partial class Default3 : System.Web.UI.Page
{
string sFullName = "";
int firstRow = 0;
private int selectedIndex;
protected void Page_Load(object sender, EventArgs e)
{
sFullName = "";
firstRow = -1;
if (!IsPostBack)
{
bool bTest = loginToWS();
if (bTest == true)
{
gvCustomers.Visible = true;
}
}
}
private bool loginToWS()
{
//code to login to web service and fetch the object filled with data.
}
private static DataTable dtInfoPersonnel(Organization org)
{
string RowId = "";
string PersonId = "";
bool firsttime = true;
DataRow dr;
DataTable dtTemp = new DataTable();
dtTemp.Columns.Add("V", System.Boolean.FalseString.GetType());
dtTemp.Columns.Add("NT", System.Boolean.FalseString.GetType());
dtTemp.Columns.Add("P");
dtTemp.Columns.Add("FN");
dtTemp.Columns.Add("MN");
dtTemp.Columns.Add("LN");
dtTemp.Columns.Add("Title");
dtTemp.Columns.Add("Remove");
dtTemp.Columns.Add("Vacant", System.Boolean.FalseString.GetType());
dtTemp.Columns.Add("Status");
dtTemp.Columns.Add("RowId");
dtTemp.Columns.Add("PersonId");
dtTemp.Columns.Add("Verified", System.Boolean.FalseString.GetType());
dtTemp.Columns.Add("Substitute", System.Boolean.FalseString.GetType());
dtTemp.Columns.Add("ComputerUser", System.Boolean.FalseString.GetType());
dtTemp.Columns.Add("YearsExperience");
dtTemp.Columns.Add("Closed", System.Boolean.FalseString.GetType());
dtTemp.Columns.Add("AP", System.Boolean.FalseString.GetType());
dtTemp.Columns.Add("CU", System.Boolean.FalseString.GetType());
dtTemp.Columns.Add("PF", System.Boolean.FalseString.GetType());
dtTemp.Columns.Add("historicAlphaCode");
foreach (K12Personnel person in org.persons)
{
//Code to fill DATATABLE with the data.
}
return dtTemp;
}
protected void Gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(gvCustomers, "Select$" + e.Row.RowIndex.ToString()));
//We're only interested in Rows that contain data
//get a reference to the data used to databound the row
DataRowView drv = ((DataRowView)e.Row.DataItem);
if (sFullName == drv["FN"].ToString() + drv["LN"].ToString())
{
//If it's the same category as the previous one
//Increment the rowspan
for (int cellCount = 0; cellCount < 6; cellCount++)
{
if (gvCustomers.Rows[firstRow].Cells[cellCount].RowSpan == 0)
gvCustomers.Rows[firstRow].Cells[cellCount].RowSpan = 2;
else
gvCustomers.Rows[firstRow].Cells[cellCount].RowSpan += 1;
//Remove the cell
e.Row.Cells.RemoveAt(0);
}
}
else //It's a new category
{ //Set the vertical alignment to top
e.Row.VerticalAlign = VerticalAlign.Top;
//Maintain the category in memory
sFullName = drv["FN"].ToString() + drv["LN"].ToString();
firstRow = e.Row.RowIndex;
}
}
}
catch (Exception ex)
{
}
}
protected void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
DataTable dtTemp1 = new DataTable();
dtTemp1 = (DataTable)Session["PersonnelInfo"];
dtTemp1.DefaultView.Sort = "LN " + "ASC";
gvCustomers.DataSource = dtTemp1;
gvCustomers.PageIndex = e.NewPageIndex;
gvCustomers.DataBind();
}
protected void btnViewDetails_Click(object sender, EventArgs e)
{
this.updPnlCustomerDetail.Update();
this.mdlPopup.Show();
}
When I run the code. It does display me the gridview but I see a error "Invalid Character" at the bottom left corner of the browser. The paging works but when I click on Details button the whole gridview disappears.
It might be because of this line:
OnClientClick="alert(’Sorry, but I didnt implement save because I dont want my northwind database getting messed up.’); return false;"
You need to use ' instead of ’
This jsfiddle confirms my suspicion.