I have a Gridview.I placed checkbox on each row.By selecting the checkbox and clicking on delete button i should get all the selected row of that gridview in the codebehind.Please do help me...
<asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" style="margin-left: 58px; margin-top: 13px" >
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Delete" runat="server" Text="Button" runat="server"
onclick="Delete_Click" />
codebehind
protected void Button1_Click(object sender, EventArgs e)
{
string valueForDB = DatabaseList.SelectedValue;
Data obj = new Data();
if (valueForDB == "virtualworkplace")
{
obj.getDocforVirtualwrkspace(valueForDB);
GridView1.DataSource = obj.getDocforVirtualwrkspace(valueForDB);
GridView1.DataBind();
}
What to write here???
protected void Delete_Click(object sender, EventArgs e)
{
}
Try this
private void DeleteRows()
{
foreach (GridViewRow row in gridView1.Rows)
{
HtmlInputCheckBox chk = (HtmlInputCheckBox) row.Cells[0].FindControl("selectedrowchk");
if (chk != null && chk.Checked)
{
string id = gridView1.DataKeys[row.RowIndex].Value.ToString(); // get the record's ID of this row
deleteRecord(id);
}
}
//RefreshGrid();
}
This code is assuming you set the DataKeyNames property of the GridView to store the primary key of each record. It is also assuming you are putting the checkbox in the first column
to set datakeys use the datakeynames property from the gridview
<asp:GridView AllowSorting="true" AutoGenerateColumns="false" AllowPaging="true"
PageSize="10" DataKeyNames="MembershipNo"
ID="grdvw_showdetails" runat="server" CellPadding="4"
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 ,whenever user will click on row of gridview view ,
record will be populated in the textbox ,but i am getting error as
index was out of range. must be non-negative and less than the size of
the collection
also i check gridview.row.count is showing zero.
please help below is my code
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" ShowHeader="false" AllowPaging="false" AllowSorting="false" ToolTip="Click Here To Edit"
Style="table-layout: fixed;" OnRowDataBound="GridView1_RowDataBound"
CssClass="mGrid" PagerStyle-CssClass="pgr" DataKeyNames="AcheadID"
AlternatingRowStyle-CssClass="alt" Width="100%" Height="100%" >
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:TemplateField ItemStyle-Width="40px">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Account Head ID" DataField="AcheadID" HeaderStyle-HorizontalAlign="Left" Visible="false" />
<asp:TemplateField HeaderText="Account Head" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="400px">
<ItemTemplate>
<asp:Label ID="lblac_head" runat="server" Text='<%# Bind("ac_head") %>'></asp:Label>
<asp:HiddenField ID="hndacheadID" runat="server" Value='<%# Bind("AcheadID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnTest" runat="server" OnClick="GridView1_OnClick" style="display:none;" />
my codebehind as
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetAccountHead();
}
}
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField hndac_headid = (HiddenField)e.Row.FindControl("hndac_headid");
if (hndac_headid.Value != "0")
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#d3d3d3'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''");
e.Row.Attributes.Add("style", "cursor:pointer;");
//e.Row.Attributes.Add("onclick", "location='patron_detail.aspx?id=" + e.Row.Cells[0].Text + "'");
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(btnTest, e.Row.RowIndex.ToString());
}
}
}
protected void GridView1_OnClick(object sender, EventArgs e)
{
Button buttonSender = sender as Button;
int index;
GridViewRow row = null;
if (int.TryParse(Request.Params.Get("__EVENTARGUMENT"), out index))
{
row = GridView1.Rows[index];
Label ac_head = (Label)GridView1.Rows[index].FindControl("lblac_head");
}
Index out of range issue happens because Request.Params.Get("__EVENTARGUMENT") doesn't works for Button ( and addiionally ImageButton ) controls.
The Button controls and ImageButton controls does not call the __doPostBack function. Because of this, the _EVENTARGUMENT ( and _EVENTTARGET as well ) will always be empty.
However, other controls such as CheckBoxes, DropDownLists, LinkButtons uses javascript function __doPostBack to trigger a postback.
Try using a LinkButton
As a second check( can be ignored ), just make sure Data is binded to GridView properly like check the IsPostback conditions etc...
Check your GridView, it has an Id GridView2 but you always referencer GridView1.
I have a gridview which have some columns. I have made name column as a hyperlink.
I have a table named- 'tblAdd'. On Page load event I made it invisible. I want that when I click column hyperlink, table display.
How can I do this using asp.net ?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Name"
DataSourceID="SqlDataSource1" OnCheckedChanged="sellectAll"
>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="sellectAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name"
SortExpression="Name" >
<ItemTemplate>
<asp:HyperLink ID="linkName" runat="server" Text='<%#Bind("Name") %>' OnClick="displayTutorial_Click" NavigateUrl='#'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My Default.aspx.cs-
protected void Page_Load(object sender, EventArgs e)
{
Label1.Visible = false;
GridView1.Columns[2].Visible = false;
//GridView1.DataBind();
if (!Page.IsPostBack)
{
fillLanguageGrid();
tblAdd.Visible = false;
}
}
Do it using Grid View row command event.
Do something like this-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//To get the Selected link text field on textbox
if (e.CommandName == "displayLink")
{
txtEditName.Text=((LinkButton)e.CommandSource).Text;
}
}
On default.aspx-
<asp:TemplateField HeaderText="Name" SortExpression="Name" >
<ItemTemplate>
<asp:LinkButton ID="linkName" runat="server" Text='<%#Bind("Name")%>' OnClick="linkBtn_Click" CommandName="displayLink"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Button btnAddrecord = (Button)sender;
GridViewRow gvr =(GridViewRow)btnAddrecord.NamingContainer;
if (btnAddrecord.CommandName == "onAddMaterial")
Define the button in your grid view markup and assign a CommandName value to the button, like this:
<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server"
OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Add Record">
<ItemTemplate>
<asp:Button ID="btnAddRecord"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>"
CommandName="AddRecord" runat="server" Text="Add" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now in your code-behind, you can handle the OnRowCommand event and AddRecord command, like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddRecord")
{
// Get index of row passed as command argument
int index = Convert.ToInt32(e.CommandArgument.ToString());
// Your logic here
}
}
1.Give a command name for button..
2.Then inside gridview
if e.commandname="yourcommandname"
{
//your code..
}
<!--We use onrowcommand for getting the selected row -->
<asp:GridView runat="server" ID="gvTest" AutoGenerateColumns="False" OnRowCommand="gvTest_OnRowCommand" >
<Columns>
<asp:TemplateField HeaderText="BookId" >
<ItemTemplate>
<asp:Label runat="server" ID="lblBookId" Text='<%# Bind("[BookId]") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtBookId" Text='<%# Bind("[BookId]") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:TemplateField>
<asp:TemplateField HeaderText="Options">
<ItemTemplate>
<asp:Button runat="server" ID="btnDelete" CommandArgument="<%# Container.DisplayIndex %>" CommandName="IsDelete" Text="Delete"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
//Code Behind
protected void gvTest_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
//getting rowindex which we have selected by using CommandArgument
int rowindex = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "IsDelete")
{
int bkid = gvTest.Rows[rowindex].Cells[0].FindControl("BookId");
//call a method to delete book using the bkid
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
I have a Gridview
<asp:GridView ID="GridView1" runat="server" Width="400px" AutoGenerateColumns="false"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="name">
<ItemTemplate>
<asp:Label ID="lblStudentName" runat="server" Text='<%# Eval("StudentName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:Label ID="lblResidentialAddress" runat="server" Text='<%# Eval("ResidentialAddress") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and i get the value binded to the gridview
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt = objdb.GetData("Getsamples", new object[] { });
ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
{
Response.Write(GridView1.SelectedRow.Cells[0].Text);
// string selectedText = ((Label)GridView1.SelectedRow.FindControl("lblStudentName")).Text;
// Response.Write(selectedText);
}
i cannot able to retrive the row where the checkbox is checked...
How to select particular row in a gridview, and based upon the selection i need to take out the 'Name' and pass this as a parameter to get ,another gridview related to the row which i selected.???
any help...
Try using another event - OnSelectedIndexChanging (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.selectedindexchanging.aspx)
It has GridViewSelectEventArgs (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewselecteventargs_members.aspx) passed to the event handler which has NewSelectedIndex property.
Your event handler will look like:
void GridView1_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
GridViewRow row = GridView1.Rows[e.NewSelectedIndex];
}