Here is my gridview and the event that fires when a user clicks on the edit button within the row. for some reason my datakey value is crashing the program saying it is null. im not sure why. the DataKeyNames in the gridview is exactly what I want it to be, formID. this is correct because the last column in the gridview, as you can see, shows me the formID and it displays just fine. so i have no idea where i am going wrong.
<asp:GridView ID="gvHistory" runat="server" DataSourceID="ObjectDataSource"
AutoGenerateColumns="False" CellPadding="10" CellSpacing="5"
CssClass="userHistory" DataKeyNames="formID">
<Columns>
<asp:BoundField DataField="clientName" HeaderText="User" />
<asp:BoundField DataField="formName" HeaderText="Form" />
<asp:BoundField DataField="dateCreated" HeaderText="Date Created" />
<asp:BoundField DataField="dateRevised" HeaderText="Last Revision Date" />
<asp:BoundField DataField="dateSubmitted" HeaderText="Date Submitted" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="edit" runat="server" CausesValidation="false" CommandName="editForm"
Text="Edit" OnDataBinding="btnEdit_DataBinding" OnClick="btnEdit_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="delete" runat="server" CausesValidation="false" CommandName=""
Text="Delete" OnDataBinding="btnDelete_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="formID" />
</Columns>
</asp:GridView>
protected void btnEdit_Click(object sender, System.EventArgs e)
{
Session["formID"] = gvHistory.SelectedDataKey.Value;
Label1.Text = Session["formID"].ToString();
}
If you are using CommandName with your item template then You can simply use Row_Command event, you don't need to create separate handler for button click.
protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "editForm")
{
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
string value=grdView.DataKeys[row.RowIndex].Values["myDataKey"].ToString();
}
}
Button btn = (Button)sender;
GridViewRow gvrow = (GridViewRow)btn.NamingContainer;
if (gvrow != null)
{
//Get the Row Index
int rowIndex = gvrow.RowIndex;
//Get the DataKey value
Session["formID"] = gvHistory.DataKeys[rowIndex].Value.ToString();
Label1.Text = Session["formID"].ToString();
}
Related
I have one checkbox with ID=checkbox1 in Asp.net gridview. I want to use checkbox1 in if else condition in backend C# code.My problem is I am not getting how to call checkbox1 as it is not showing in the backend.
Thanks in advance.
My code is
if (txtsender.Text != String.Empty && checkbox1.checked==true)
{
chklist();
}
One view to access your checkbox inside Gridview is to loop on grid view rows and find your checkbox. Code example given below to access gridview checkbox in button click event
Aspx code
<asp:GridView ID="gv1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkBox" runat="server" AutoPostBack="true" Text="T1" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="Submit" />
Aspx.cs Code
protected void btn_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gv1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox c = (CheckBox)row.FindControl("chkBox");
if (c.Checked)
{
}
}
}
}
I have gridview control it contains 6 columns when i click 6th column row of gridview i need to selecte that contains columns row text into a string. how can i take here i am taking commandargument is a string and how can i take another column names text
my code:
<asp:GridView ID="GridView1" Width="950px" CssClass="Grid" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:GridView ID="GridView1" Width="950px" CssClass="Grid" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="" ItemStyle-ForeColor="White" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="SName" HeaderText="SName" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Size" HeaderText="Size(MB)" />
<asp:BoundField DataField="Time" HeaderText="Time" />
<asp:TemplateField HeaderText="FileName">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" CausesValidation="False" CommandArgument='<%# Eval("FileName") %>'
CommandName="Download" Text='<%# Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.No." Visible="false">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string ID1;
if (e.CommandName == "Download")
{
GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int rowIndex = gvr.RowIndex;
Label Itemid = (Label)GridView1.Rows[rowIndex].FindControl("lblID");
ID1 = (Itemid).Text;
Session["ID"] = ID1;
string filename = e.CommandArgument.ToString();
//here how can i hold another column text
}
}
I have a easiest way to do this same thing...
<asp:Label ID="lblName" runat="server" Text='<%#Eval("ID").ToString() +", "+ Eval("OtherCoulmn").ToString() %>'></asp:Label>
--- hope it helps
Also the best way is to do something like this
((MyObject)Container.DataItem).MyProperty where MyObject is the Model which you bind with grid and property which you wan to use in rowcommand its clean .
Simply follow the bellow code sample:
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
Label lblId = gvCipamMember.Rows[gvr.RowIndex].FindControl("lblPersonId") as Label;
cmd = new SqlCommand("SELECT Id,Res_Person,Email_ID,Mobile_NO,Cipam_Flag FROM Responsibilty_Master WHERE Id=#Id", con.MyConnection);
cmd.Parameters.AddWithValue("#Id", Convert.ToInt32(lblId.Text.ToString()));
dt = new DataTable();
con.MyConnection.Open();
dt.Load(cmd.ExecuteReader());
if (dt.Rows.Count > 0)
{
txtPersonName.Text = dt.Rows[0]["Res_Person"].ToString();
txtEmail.Text = dt.Rows[0]["Email_ID"].ToString();
txtMobileNo.Text = dt.Rows[0]["Mobile_NO"].ToString();
if(Convert.ToBoolean(dt.Rows[0]["Cipam_Flag"].ToString())==true)
{
chkbCipamFlag.Checked = true;
}
}
}
I'm trying to populate multiple text boxes with data from a gridview when I click the link button (which is in fact the name of one of the fields in each row) but it isn't going through. I'm new to this - literally my first time. Any help would be most appreciated.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
AccountNumber.Text = selectedRow.Cells[1].Text;
Name.Text = selectedRow.Cells[1].Text;
Address1.Text = selectedRow.Cells[1].Text;
Address2.Text = selectedRow.Cells[2].Text;
Address3.Text = selectedRow.Cells[3].Text;
PhoneNumber.Text = selectedRow.Cells[4].Text;
FaxNumber.Text= selectedRow.Cells[5].Text;
CurrencyID.Text = selectedRow.Cells[6].Text;
}
}
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="Agent_Account_No"
DataSourceID="SqlDataSource1"
AlternatingRowStyle-BackColor ="Lavender"
HeaderStyle-BackColor="#9966FF"
AllowSorting="True" HeaderStyle-BorderColor="Black"
HorizontalAlign="Center"
RowStyle-BorderColor="Black"
EmptyDataText="There are no data records to display."
onrowcommand ="GridView1_RowCommand">
<AlternatingRowStyle BackColor="#CCFFCC" />
<Columns>
<asp:BoundField datafield="Agent_Account_No" HeaderText="Account No"
ItemStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="50"
SortExpression="Agent_Account_No"
ReadOnly="true">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"
Width="50px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Name" SortExpression="Agent_Name">
<ItemTemplate>
<asp:LinkButton ID="AgentName" runat="server"
Text='<%# Eval("Agent_Name") %>'
CommandName="Select"
CommandArgument='<%#Bind("Agent_Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
I got it to work this way - using help from this site:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
AccountNumber.Text = GridView1.DataKeys[row.RowIndex]["Agent_Account_No"].ToString();
......
}
I don't know if this declaration is right, but it works. However now that it works I see a problem that I didn't see before - see my profile and thanks a lot!
I would highly recommend using TemplateFields for all of your columns, like this:
Markup:
<Columns>
<asp:TemplateField HeaderText="Account No" SortExpression="Agent_Account_No">
<ItemTemplate>
<asp:Label ID="LabelAccountNumber" runat="server"
Text='<%# Eval("Agent_Account_No") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
...
<asp:TemplateField HeaderText="Name" SortExpression="Agent_Name">
<ItemTemplate>
<asp:LinkButton ID="AgentName" runat="server"
Text='<%# Eval("Agent_Name") %>'
CommandName="Select"
CommandArgument='<%#Bind("Agent_Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Now in the RowCommand method, you can use the FindControl() method of the grid view row to get to the text you are interested in, like this:
Code-behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
// Find the account number label to get the text value for the text box
Label theAccountNumberLabel = selectedRow.FindControl("LabelAccountNumber") as Label;
// Make sure we found the label before we try to use it
if(theAccountNumberLabel != null)
{
AccountNumber.Text = theAccountNumberLabel.Text;
}
// Follow the same pattern for the other labels to get other text values
}
}
I have a GridView bound to an object datasource and a hover menu extender over that. On the panel that pops up I have two buttons - one for delete and one for edit. The problem I'm having is identifying which row triggered the hover menu so I know what to delete. I've searched all over the site and found similar issues but I wasn't able to apply them properly. I followed this video, and was able to get a hidden field to maintain the ID but only of the last row that was created, so my delete button always removed the last entry. I hope that was somewhat clear..
Here is my gridview code:
<asp:GridView runat="server" AutoGenerateColumns="False"
DataSourceID="source_Layout_view" ID="GridView1"
onrowdatabound="GridView1_RowDataBound"
onrowcreated="GridView1_RowCreated">
<Columns>
<asp:BoundField DataField="type" HeaderText="type" SortExpression="type" />
<asp:BoundField DataField="code" HeaderText="code" SortExpression="code" />
<asp:BoundField DataField="description" HeaderText="description"
SortExpression="description" />
<asp:BoundField DataField="position" HeaderText="position"
SortExpression="position" />
<asp:BoundField DataField="sequence" HeaderText="sequence"
SortExpression="sequence" />
<asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="img_edit" runat="server" ImageUrl='~/ui/images/wrench.png' Width="25px" Height="25px" />
<asp:HoverMenuExtender ID="gridview_options_extender" runat="server" PopupControlID="gridview_options_popup" TargetControlID="img_edit"
OffsetX="10" OffsetY="10" PopupPosition="Right" PopDelay="50" HoverDelay="50" >
</asp:HoverMenuExtender>
<asp:Panel ID="gridview_options_popup" runat="server">
<asp:Button ID="btn_popup_delete" runat="server" Text="Delete Unit" OnClick="deleteRow"/>
<br />
<asp:Button ID="btn_popup_edit" runat="server" Text="Edit Unit" />
<asp:HiddenField ID="tellmeRow" runat="server" Value='Eval("ID")'/>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and here is my code behind
protected void deleteRow(object sender, EventArgs e)
{
Button b = sender as Button;
Panel x = b.Parent as Panel;
HiddenField whatiwant = (HiddenField)x.FindControl("tellmeRow");
int idForDeletion = Int32.Parse(whatiwant.Value);
using (var context = new cocoEntities())
{
context.CoCo_Current.DeleteObject(context.CoCo_Current.Single(o => o.ID == idForDeletion));
context.SaveChanges();
}
Response.Redirect("default.aspx");
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HoverMenuExtender menu = (HoverMenuExtender)e.Row.FindControl("gridview_options_extender");
e.Row.ID = e.Row.RowIndex.ToString();
menu.TargetControlID = e.Row.ID;
}
}
}
Don't use button click handler to do some action on a GridView. Assign instead apropriate CommandName property value for button and handle GridView's RowCommand event. GridView.RowCommand Event
I have this gridview:
<div class="content">
<asp:GridView ID="DocumentGrid" runat="server" AutoGenerateColumns="False" OnRowCommand="DocumentGrid_RowCommand" >
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-Width="120px"/>
<asp:ButtonField HeaderText="Download Link" Text="Download"/>
</Columns>
</asp:GridView>
</div>
As you can see, DocumentGrid_RowCommand is called when the "Download" button is pressed, How can I find out what the values are of the row that was clicked?
If more than one button fields are there in GridView, set CommandName attribute. That way we can determine which button is pressed in RowCommand event. So always set commandName attribute.
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-Width="120px"/>
<asp:ButtonField HeaderText="Download Link" Text="Download" CommandName="cmd"/>
</Columns>
In RowCommand event handler, GridViewCommandEventArgs.CommandArgument property returns index of row on which button is pressed.
protected void DocumentGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmd")
{
int index = int.Parse(e.CommandArgument.ToString());
GridViewRow row = DocumentGrid.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
Response.Write(row.Cells[0].Text);
}
}
}
If you set the markup like this,
<Columns>
<asp:TemplateField HeaderText="Download">
<ItemTemplate>
<asp:Button ID="btnDownload" CommandName="Download" CommandArgument='<%# Container.DataItemIndex %>'
runat="server" Text="Download" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
on the code-behind you can check the CommandArgument like this:
if (e.CommandName == "Download")
{
int index = Convert.ToInt32(e.CommandArgument);
}