I am trying to get the selected row data and transfer it to a label on the same page. However I cannot get the Gridview.SelectedRow to work with my CommandName. I have tried everything....
I get the error. Object reference not set to an instance of an object. on Label2.Text
Here is my Code:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Grab")
{
Label2.Text = GridView1.SelectedRow.Cells[2].Text;
Label3.Text = GridView1.SelectedRow.Cells[3].Text;
Label4.Text = GridView1.SelectedRow.Cells[4].Text;
Label5.Text = GridView1.SelectedRow.Cells[5].Text;
}
}
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="ID" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" CssClass="td" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Width="574px" onrowcommand="GridView1_RowCommand">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/edit.png" OnClick="ImageButton2_Click" />
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="Select" ImageUrl="~/images/delete.png" onclientclick=" return confirm('Are you want to Delete this Vehicle?');" />
<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="~/images/refre.png" CommandName="Grab" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Year" HeaderText="Year" SortExpression="Year" />
<asp:BoundField DataField="Make" HeaderText="Make" SortExpression="Make" />
<asp:BoundField DataField="Model" HeaderText="Model" SortExpression="Model" />
<asp:BoundField DataField="Submodel" HeaderText="Submodel" SortExpression="Submodel" />
<asp:BoundField DataField="ISENABLED" HeaderText="ISENABLED" SortExpression="ISENABLED" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Try something like this. Since you're trying to access the values in the command event and not in the OnSelectedIndexChanged event you need to get hold of the row triggering the command event first.
if (e.CommandName == "Grab")
{
GridViewRow row = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
if (row != null)
{
Label2.Text = row.Cells[2].Text;
Label3.Text = row.Cells[3].Text;
Label4.Text = row.Cells[4].Text;
Label5.Text = row.Cells[5].Text;
}
}
Related
I have a gridview that should split into pages but the issue is that when I change the page the whole gridview is disappearing I tried everything I found in the internet but with no solution here is my code
<asp:GridView ID="ExistContents" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None"
AllowPaging="true" PageSize="5" OnPageIndexChanging="ExistContents_PageIndexChanging" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="ContentID" HeaderText="id" />
<asp:ImageField DataImageUrlField="TmpFilename" HeaderText="Image">
<ControlStyle Height="64px" Width="96px" />
</asp:ImageField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:BoundField DataField="ContentID" HeaderText="id" Visible="false" ShowHeader="false" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:CheckBox runat="server" ID="ChBox1" OnCheckedChanged="ExistContents_CheckedChanged" AutoPostBack="True"/>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" CssClass="header"/>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
and here is the event handler
protected void ExistContents_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
ExistContents.PageIndex = e.NewPageIndex;
List<CONTENT> panier;
panier = (List<CONTENT>)Session["PANIER"];
ExistContents.DataSource = panier;
ExistContents.DataBind();
}
You should handle the PageIndexChanged event instead.
The pageIndexChanging is made to give you an option to cancel the paging before it's executed.
here is an answer for this probleme, acctually my datasource was not the session but a linq query so i changed it and it works perfectly
and here is my new code
protected void ExistContents_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow gr = (GridViewRow)chk.Parent.Parent.Parent.Parent;
int id= Convert.ToInt32(gr.Cells[0].Text);
if (chk.Checked)
AddToCaddy(id, "DELETE");
else
DeleteFromCaddy(id);
UpdatePanel.DataBind();
UpdatePanel.Update();
}
just for information if you are making a databind to your gridview in the Page_Load inside the if (!IsPostBack) then you will need to redefind the dataSource but if you'r not then you only need to use these functions
UpdatePanel.DataBind();
UpdatePanel.Update();
i hope this helps
I'm trying to add a Register button to every row in my course gridview so that when the user click on the register button on that particular row, it will register him to that particular course on that row by adding a course registration record into sql.
How should I write my code to insert that row's data into sql?
C#:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Register")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
}
ASP.NET:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCommand="GridView1_RowCommand" Width="394px">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True"></asp:BoundField>
<asp:BoundField DataField="SpeakerName" HeaderText="Speaker" ReadOnly="True" />
<asp:BoundField DataField="startdate" HeaderText="Date" ReadOnly="True" />
<asp:BoundField DataField="Capacity" HeaderText="Capacity" />
<asp:TemplateField HeaderText="Button" ShowHeader="False">
<ItemTemplate>
<asp:Button ID="RegButton" runat="server" CausesValidation="false" CommandName="Register"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Register" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Select" SelectText="Details" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
first you should add course Id (primary key) as datakeynames property to GridView1,and then can get the Id on GridView1_RowCommand like below :
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Register")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int courseId = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
//your other codes
}
so,you have your course Id and by selecting the record you can add current record to sql.hope it helps.
Edit :
also you don't need this part CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" in your aspx page any more
What I need to do is to highlight each row when it is processing to show the process progress, the gridview may contain almost one thousands of row. below is the code I have written but which doesn't work.
Please can someone help me.
<
asp:GridView ID="gdview1" runat="server" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Vertical" Font-Names="Calibri"
Font-Size="Small" AutoGenerateColumns="False"
OnRowDataBound="gdview1_RowDataBound"
OnSelectedIndexChanged="gdview1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkBxHeader" OnCheckedChanged="chkSelect_CheckedChanged" AutoPostBack="true" runat="server" />
</HeaderTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkNUM" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkNUM" runat="server" DataField="ColNUM" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Row#">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ColNUM" HeaderText="Contract #" />
<asp:BoundField DataField="Col1" HeaderText="Suffix" />
<asp:BoundField DataField="Col2" HeaderText="First Name" />
<asp:BoundField DataField="Col3" HeaderText="Last Name" />
<asp:BoundField DataField="Col4" HeaderText="Street" />
<asp:BoundField DataField="Col5" HeaderText="City" />
<asp:BoundField DataField="Col6" HeaderText="Zip" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butChargeCreditCards_Click(object sender, EventArgs e)
{
DataTable tblContrts = (DataTable) Session["tblContrts"];
foreach (GridViewRow row in gdview1.Rows)
{
CheckBox chkbx = (CheckBox) row.FindControl("chkNUM");
if (chkbx != null && chkbx.Checked)
{
gdview1_SelectedIndexChanged(row,e);
string SS = chkbx.Text.ToString();
string strResults = method1;
}
}
}
protected void gdview1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gdview1.Rows)
{
if (row.RowIndex == gdview1.SelectedIndex)
{
row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
}
else
{
row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
}
}
}
}
}
Have you tried it by using the "OnRowDataBound" or "OnRowCreated" Event of the Grid and write the color-highliting in code behind?
Something like this?
http://www.java2s.com/Code/ASP/ADO.net-Database/UsingtheRowCreatedEventtoprogrammaticallychangethestyle.htm
But maybe you have a problem because the loading would be too fast to really notice?
SQL Server table structure:
ChapName varchar(200)
Status varchar(1)
Requirement:
I want to display checkbox in an ASP.NET gridview from Visual Studio 2010
if the value of status column is T, let it be checked and unchecked otherwise.
but it shows only textbox.
I have tried <asp:templatefield> and <asp:itemtemplate> but it throws error if I try to bind this checkbox.
any sample code is required as I am beginner in this field.
The code I tried:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
CheckBox c = (CheckBox)GridView1.FindControl("ChkStatus");
TextBox TB = (TextBox)GridView1.FindControl("Status");
//Response.Write(TB.Text);
if (TB.Text == "T")
{
c.Checked = true;
}
else
{
c.Checked = false;
}
}
The error I got
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.
Exception Details:
System.NullReferenceException: Object reference not set to an instance
of an object.
Aspx markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Comp,QTypeCode" DataSourceID="SDS_QType_Edit"
BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
BorderWidth="1px"
CellPadding="4" ForeColor="Black" GridLines="Vertical"
AllowPaging="True" AllowSorting="True"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="QTypeCode" HeaderText="QTypeCode"
SortExpression="QTypeCode" InsertVisible="False"
ReadOnly="True" />
<asp:BoundField DataField="Descr" HeaderText="Descr" SortExpression="Descr" />
<asp:CheckBoxField DataField="AnsReq" HeaderText="AnsReq" ReadOnly="True"
SortExpression="AnsReq" />
<asp:CheckBoxField DataField="OptionPrint" HeaderText="OptionPrint"
ReadOnly="True" SortExpression="OptionPrint" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
<asp:BoundField DataField="TransDate" HeaderText="TransDate"
SortExpression="TransDate" />
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName" />
<asp:TemplateField HeaderText="Check Box" >
<ItemTemplate>
<asp:CheckBox ID ="ChkStatus" Text="text" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle Wrap="False" />
<EmptyDataRowStyle Wrap="False" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle Wrap="False" BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle Wrap="False" BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White"
Wrap="False" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Assume you have grid defined as below on asmx
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ChapName" HeaderText="ChapName" />
<asp:TemplateField HeaderText="Status" Visible ="false">
<ItemTemplate>
<asp:Label ID="Status" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Check Box" >
<ItemTemplate>
<asp:CheckBox ID ="ChkStatus" Text="text" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
on Row Data Bound event you can find controls as below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
CheckBox c = e.Row.FindControl("ChkStatus") as CheckBox;
Label lbl = e.Row.FindControl("Status") as Label;
if (c!= null && lbl != null )
{
c.Checked = (lbl.Text == "T");
}
}
I have a GridView that is built from a Linq query as follows
var GridViewLoad = from d in QVuser.QlikViewDashboards.AsEnumerable()
join p in tempPermissions.AsEnumerable() on d.DashboardId equals Convert.ToInt32(p["DashboardId"])
where Convert.ToInt32(p["UserId"]) == GridViewUser
select new
{
DashboardId = d.DashboardId,
PermissionId = Convert.ToInt32(p["PermissionId"]),
DashboardName = d.DashboardName,
Operational_Unit = p["Operational_Unit"].ToString(),
Cost_Centre = p["Cost_Centre"].ToString(),
Project = p["Project"].ToString(),
Fund = p["Fund"].ToString()
};
GridView1.DataSource = GridViewLoad;
GridView1.DataKeyNames = new string[] {"PermissionId"};
GridView1.DataBind();
Then the GridView is defined as:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3"
GridLines="Vertical" ShowHeaderWhenEmpty="True" OnRowDeleting="GridView1_RowDeleting"
style="text-align: center" BackColor="White" BorderColor="#999999"
BorderStyle="None" BorderWidth="1px" Width="550px"
>
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="Delete" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="false"
CommandArgument='<%# Eval("PermissionId") %>' CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PermissionId" HeaderText="ID"/>
<asp:BoundField DataField="DashboardName" HeaderText="Dashboard" ReadOnly="True" SortExpression="DashboardName" />
<asp:BoundField DataField="Operational_Unit" HeaderText="Operational_Unit" ReadOnly="True" SortExpression="Operational_Unit" />
<asp:BoundField DataField="Cost_Centre" HeaderText="Cost_Centre" ReadOnly="True" SortExpression="Cost_Centre" />
<asp:BoundField DataField="Fund" HeaderText="Fund" ReadOnly="True" SortExpression="Fund" />
<asp:BoundField DataField="Project" HeaderText="Project" ReadOnly="True" SortExpression="Project" />
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" BorderStyle="Solid" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" BorderStyle="Solid"
BorderWidth="1px" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
What I want to do is hide the PermissionId field from sight, but it obviously still needs to be there for the Delete button to work..
Can someone help me out with this?
I've tried setting Visible="false", which hides it, but then my delete button stops working..
Cheers for your help..
Since you're setting the DataKeyNames, you should be able to retrieve the permission ID from the index of the row being deleted, like so:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int permissionId = (int)GridView1.DataKeys[e.RowIndex].Value;
DoDelete(permissionId);
}
This should work whether the column is visible or not.
Try
<asp:BoundField DataField="PermissionId" HeaderText="ID" Visible="False"/>