ASP.NET Grid View Problem - asp.net

I have one gridview where I am passing the command argument as gridview row id for the Button I created for every row.
I want to display all the details of that row in the textbox according to the Row clicked.
<asp:GridView ID="gvCategory" runat="server" AutoGenerateColumns="false"
onrowcommand="gvCategory_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatId" runat="server" Text='<%#Eval("categoryId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatName" runat="server" Text='<%#Eval("categoryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnModify" runat="server" Text="Modify" CommandName="Modify" CommandArgument='<%#Eval("categoryId") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code.....
if (e.CommandName == "Modify")
{
int id = Convert.ToInt32(e.CommandArgument);
// I want the value to assgin for the selected row here
// I was previously fetching the data from database according id,but i want this frim the gridview of selected row.
}

I wrote a quick example of how to do what you're trying to do. It works for me.
The Example Solution
Default.aspx
<asp:GridView ID="myGridView" runat="server"
AutoGenerateColumns="False"
DataSourceID="StudentsDS"
DataKeyNames="ID"
OnRowCommand="myGridView_RowCommand"
OnSelectedIndexChanged="myGridView_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="FullName" HeaderText="FullName"
SortExpression="FullName" />
<asp:BoundField DataField="ClassID" HeaderText="ClassID"
SortExpression="ClassID" />
<asp:CommandField ShowSelectButton="True" SelectText="Modify" />
</Columns>
</asp:GridView>
<asp:TextBox ID="txtStudent" runat="server" />
<asp:SqlDataSource ID="StudentsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:Sandbox %>"
SelectCommand="SELECT * FROM Student"
/>
Default.aspx.cs
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
// do something here if you want, although not necessary
}
}
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
// show "FullName" field of selected row in textbox
txtStudent.Text = myGridView.SelectedRow.Cells[1].Text;
}
How It Works
Upon clicking "Modify" in a row, the textbox updates to show the FullName field of the selected row.
The important part is that instead of a TemplateField, use a CommandField with ShowSelectButton="True". Then do what you need to do in the SelectedIndexChanged event handler. Note that the SelectText of the CommandField is set to "Modify" as you desired. You can also set the ButtonType property of the CommandField to be button, image, or link.
Making It Better
I would also advise that instead of using a SqlDataSource as I have, you use an ObjectDataSource so that you can do something like
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
MyModelObject o = myGridView.SelectedRow.DataItem as MyModelObject;
txtStudent.Text = o.MyProperty;
}
You may also consider wrapping your GridView in an UpdatePanel to prevent full postbacks / page refreshes.

After you have the lineID, you select that line, and then you have the CategoryID on selected value
int iTheIndexNow = Convert.ToInt32(e.CommandArgument);
// select that line to see it visual as selected, and get the value on next line
gvCategory.SelectedIndex = iTheIndexNow;
// here is your categoryID that
//you can use to open your database with and get the text
gvCategory.SelectedValue // == categoryID
On GridView you must have set your KeyID
<asp:GridView DataKeyNames="categoryId" .... >

Related

Showing url in BoundField in gridview

I am developing a chatting web application with the help of the gridview....The problem is when the user enter the link and it is saved in the database and when the data is retrieved in the gridview the link should be click able. The field I am using to retrieve the data is BoundField.
I don't want to use hyperlink field because then in every row there will a link. I only want to display link when a user will enter a link.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="AccessDataSource1" CssClass="amit1" >
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="m1" HeaderText="Message" SortExpression="m1" >
<HeaderStyle Font-Size="Larger" HorizontalAlign="Left" Width="280px" />
<ItemStyle Font-Size="Medium" HorizontalAlign="Left" Width="280px" />
</asp:BoundField>
</Columns>
</asp:GridView>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/gold.accdb"
SelectCommand="SELECT [m1] FROM [Chat_detail] WHERE ([Chat_id] = ?)">
<SelectParameters>
<asp:QueryStringParameter Name="Chat_id" QueryStringField="chat_id"
Type="String" />
</SelectParameters>
</asp:AccessDataSource>
Is there is any way to do this???
Thanks in advance.
Add Hyperlink, make use of RowDataBound event to make that hyperlink visible tru/false based on the value.
See Below:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlnk = (HyperLink)e.Row.FindControl("hlnkUserEnetredLink");
if(!String.IsNullOrEmpty(hlnk))
{
hlnk.Visible = true;
}
else
{
hlnk.Visible = false;
}
}
}
Add that Hyperlink in your aspx page -- in Gridview..
You could disable the hyperlink in your code behind based on whatever condition. Note: Making visible = true/false will leave a empty cell in the gridview column.
protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// find the HyperLink defined in the fridview definition
HyperLink myHyperLink = (HyperLink)e.Row.FindControl("hpLinkUrl");
//userstoredlink is the datasource field that holds the user stored link
string userLink = DataBinder.Eval(e.Row.DataItem, "userstoredlink").ToString();
if (string.IsNullOrEmpty(userLink))
{
// disable link
myHyperLink.Enabled = false;
}
}
}
Please refer my another post on different ways to add hyperlink to gridview
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="hpLinkUrl" runat="server" NavigateUrl='<%# Eval("userstoredlink", "{0}") %>' Text="View Details" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Also remember you need to define OnRowDataBound="GridView1_RowDataBound" for your gridview.
Or if you don't want to display the ViewDetails text when there is no value for userstoredlink then changes the hyperlink definition as follows
<asp:HyperLink ID="hpLinkUrl" runat="server" NavigateUrl='<%# Eval("userstoredlink", "{0}") %>' Text='<%# Eval("userstoredlink") != "" ? "View Details" : "" %>' />

Asp.net GridView - Getting row identifier

I have a page that displays orders in GridView and each row has a details- and delete-button. Most of the time everything works fine, but if new order arrives between the page refresh and button clicking, wrong order is processed.
I save unique identifier to CommandArgument, but it seems that the identifier in question isn't passed back to server, but instead some kind of counter (e.g. 5th order) and since after the arrival of new order the right one would be 6th, everything goes wrong... What's up with that?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" PageSize="20"
EnableViewState="False" EnableSortingAndPagingCallbacks="True"
DataSourceID="ldsOrders" AllowPaging="True"
ondatabound="gvOrders_DataBound" CssClass="Gridview" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" CommandArgument='<%#Eval("ID") %>' CommandName="Delete"
Text="Delete" OnClick="btnDelete_Click" CausesValidation="False" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnOrder" runat="server" CommandArgument='<%#Eval("ID") %>' CommandName="Order"
Text="Order" OnCommand="btnOrder_Click" CausesValidation="False" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-Behind:
protected void btnDelete_Click(object sender, CommandEventArgs e)
{
string orderID = (string)e.CommandArgument;
da.DeleteOrder(Convert.ToInt32(orderID));
Response.Redirect(Request.RawUrl, false);
}
Without any code examples here is something to try...
Assuming that ID is the primary key - you should set that in the GridView DataKeys property. You should not place primary keys in a viewable area.
Where you specify the CommandArgument: that should be the rowindex that is set in the RowDataBound event such that:
//(note this is pseudo-code, but you should get the basic idea)
if( e.row.rowtype == datarow )
{
Button btn = (Button) e.row.findcontrol("btnDelete") ;
btn.CommandArgument = e.row.rowIndex ;
}
And in the delete click event obtain the primary key from the gridview datakeys:
protected void btnDelete_Click(object sender, CommandEventArgs e)
{
int orderIDIdx = (Convert.ToInt32(e.CommandArgument);
int pkey = Convert.ToInt32(Gridview1.Datakeys(orderIDidx).value
da.DeleteOrder(pkey);
Response.Redirect(Request.RawUrl, false);
}
Obviously, add appropriate error checking where applicable.
You should set the DataKeyNames
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames.aspx
<asp:GridView ID="Gridview1" DataKeyNames="ID" .... >
then the command delete trigger the RowDeleting event
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdeleting.aspx
which can be used to delete the row using e.Keys[0] to retrieve the id
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Int orderID = Convert.ToInt32(e.Keys[0].ToString());
da.DeleteOrder(Convert.ToInt32(orderID));
}

show data in outside textbox from selected row in gridview

I am having a grid view created by using template fields. I inserted a link button using template fields in the grid view.
There are 4 textboxes outside the GridView.. i want to select the row on link button's click and put the selected row's data in text boxes. I am using a row command even for this but its not working ... the syntax i am using is .:
<asp:GridView ID="gview" AutoGenerateColumns="False" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" onrowcommand="gview_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Book Name">
<ItemTemplate>
<%#Eval("book_name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Author">
<ItemTemplate>
<%#Eval("book_author") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Publisher">
<ItemTemplate>
<%#Eval("book_Publisher") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Price">
<ItemTemplate>
<%#Eval("book_Price") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:LinkButton ID="lnkDet" CommandName="cmdBind" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" runat="server" CausesValidation="false">View Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
and Code behind file :
protected void gview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmdBind")
{
LinkButton lb = (LinkButton)e.CommandSource;
int index = Convert.ToInt32(lb.CommandArgument);
//Bind values in the text box of the pop up control
txt_name.Text = gview.Rows[index].Cells[0].Text;
txt_author.Text = gview.Rows[index].Cells[1].Text;
txt_price.Text = gview.Rows[index].Cells[2].Text;
}
}
Can anyone tell me how to do this.
I think this works:
protected void gview_RowCommand(object sender, GridViewCommandEventArgs e){
if (e.CommandName == "cmdBind")
{
int index = Convert.ToInt32(e.CommandArgument);
//Bind values in the text box of the pop up control
txt_name.Text = gview.Rows[index].Cells[0].Text;
txt_author.Text = gview.Rows[index].Cells[1].Text;
txt_price.Text = gview.Rows[index].Cells[2].Text;
}}
Attempting it the way you are is not impossible, but it may be easier to just use the in built select buttons for each row. That way you can just use the SelectedIndexChanged event of the gridview:
protected void gview_SelectedIndexChanged(object sender, EventArgs e)
{
txt_name.Text = gview.SelectedRow.Cells[0].Text;
txt_author.Text = gview.SelectedRow.Cells[1].Text;
txt_price.Text = gview.SelectedRow.Cells[2].Text;
}

ASP- Get a GridRow value / OnClick method

I'm working on a C#/ASP 4.0 project where I'm trying to make a shopping cart application.
There is a GridView on my Products page that shows all of the items, and I want the user to be able to click an "Add to Cart" button field in this GridView which will, obviously, add an item to their cart.
I'm having issues actually setting an OnClick event for the gridview, though? That doesn't seem to be available in the Event menu in the Properties. Additionally, I can't seem to figure out how to get the specific row, either. I have method that does this...
int productID = Convert.ToInt32(GridView1.Rows[n].Cells[0].Text);
AddToCart(productID);
But I have no idea how to figure out n, or how to have this method get called when they click that ButtonField in the gridview.
You could do this:
First, add a template field to the gridview:
<asp:TemplateField HeaderText="Add to Cart">
<ItemTemplate>
<asp:Button id="bthAddToCart"
CommandArgument'<%#Eval("ProductID")%>'
OnClick="bthAddToCart_Click"
Text="Add to Cart"
runat="server"/>
</ItemTemplate>
</asp:TemplateField>
Now, add the handler for the Click event of the button:
protected void bthAddToCart_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
int productID = Convert.ToInt32(button.CommandArgument);
AddToCart(productID);
}
You can use the template fields like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="30px">
<ItemTemplate>
<asp:Button ID="btnAddToCart" runat="server" Text="Add To Cart" CommandName="AddToCart"
CommandArgument='<%# Eval("ProductID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No Data Found.
</EmptyDataTemplate>
</asp:GridView>
Then on your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
int ProductID = Convert.ToInt32(e.CommandArgument);
AddToCart(ProductID);
}
}
Hope this helps! Good Luck!
Use the OnRowCommand event of the grid view. More details: here
You have to use OnRowCommand Event for Gridview. Use Following Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="30px">
<ItemTemplate>
<asp:Button ID="btnAddToCart" runat="server" Text="Add To Cart" CommandName="AddToCart"
CommandArgument='<%# Eval("ProductID") %>' />
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
In C# Code use following code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Add To Cart")
{
int ProductID = Convert.ToInt32(e.CommandArgument);
AddToCart(ProductID);
}
}

Get the ID of a record in a gridview asp.net

i have a checkbox in a template field of a gridview and i want to get the id of the record at a checkbox tick. how do i do it? i am doing asp.net and also by using datakeynames instead, my gridview also shows the datakeynames persID column. why?
my code:
<asp:GridView ID="GridViewHostelMember" runat="server" DataKeyNames="_PersID" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="_PersID" HeaderText="_PersID" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="DOB" HeaderText="DOB" />
<asp:BoundField DataField="FatherName" HeaderText="FatherName" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow item in this.GridViewHostelMember.Rows)
{
CheckBox chbTemp = item.FindControl("CheckBoxSelect") as CheckBox;
if (chbTemp != null)
{
if (chbTemp.Checked)
{
Label1.Text = item.Cells[0].Text;
}
}
}
}
_PersID is showing because autogeneratecolumns is set to true; if true, it shows all columns. To hide, set to false, and explicitly add the columns to the grid.
For the first part, at checkbox tick, you would need to set AutoPostBack="true" on the checkbox, which posts back, and then you can check the data key for the current row of the grid.
Reference -
my gridview also shows the datakeynames persID column. why?
true to automatically create bound fields for each field in the data
source; otherwise, false. The default is true.
It should be like below..
<asp:GridView ID="GridViewHostelMember" autogeneratecolumns="False"
runat="server" DataKeyNames="_PersID">
i want to get the id of the record at a checkbox tick. how do i do it?
Sample Code
protected void CheckBox_Checked(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
//c.ValidationGroup is your ID
}
Sample HTML
<asp:GridView ID="ed" runat="server" OnRowCommand="GridView_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" AutoPostBack="true" ValidationGroup='<%#Eval("ID") %>' OnCheckedChanged="CheckBox_Checked" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Resources