Getting datas from gridview for selected row? - asp.net

i'm new to asp.net. i'm doing one project. in that i've used one gridview and fetch datas from database using sqldatasource.
gridview code is
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="Library" CellPadding="4" ForeColor="#333333"
GridLines="None" OnRowDataBound="GridView1_RowDataBound" >
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:BoundField DataField="Sl_No" HeaderText="Sl_No" SortExpression="Sl_No" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Author" HeaderText="Author"
SortExpression="Author" />
<asp:BoundField DataField="Publication" HeaderText="Publication"
SortExpression="Publication" />
<asp:BoundField DataField="Available" HeaderText="Status"
SortExpression="Available" />
<asp:TemplateField HeaderText="Availability">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Available") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RIUserTaken" HeaderText="RIUserTaken"
SortExpression="RIUserTaken" Visible="False" />
<asp:TemplateField HeaderText="Taken By" ShowHeader="False">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("RIUserTaken", "{0}") %>'></asp:Label>
<asp:Button ID="SendRequest" runat="server" Text="Button" Visible="False"
onclick="SendRequest_Click" CommandName="SendRequestCmd" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Taken Date" InsertVisible="False"
ShowHeader="False">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("TakenDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" /> </asp:GridView>
code is one of the column of the grid view. if i click on that button, i've to store that button contains rows all datas in string variable. like
string slno="";
slno=gridview1.cells[0].text; (i'm not sure it is correct or not)
plz anyone help me??
thanks in advance :)

From msdn, you should check this.
GridView.SelectedIndexChanged event
void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = CustomersGridView.SelectedRow;
// Display the company name from the selected row.
// In this example, the third column (index 2) contains
// the company name.
MessageLabel.Text = "You selected " + row.Cells[2].Text + ".";
}
void CustomersGridView_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
// Get the currently selected row. Because the SelectedIndexChanging event
// occurs before the select operation in the GridView control, the
// SelectedRow property cannot be used. Instead, use the Rows collection
// and the NewSelectedIndex property of the e argument passed to this
// event handler.
GridViewRow row = CustomersGridView.Rows[e.NewSelectedIndex];
// You can cancel the select operation by using the Cancel
// property. For this example, if the user selects a customer with
// the ID "ANATR", the select operation is canceled and an error message
// is displayed.
if (row.Cells[1].Text == "ANATR")
{
e.Cancel = true;
MessageLabel.Text = "You cannot select " + row.Cells[2].Text + ".";
}
}

Do these things
Step 1. Wire up a RowCommand Evnt to your GridView
Step 2. Inside that event at code-behind, do this
if(e.CommandName.Equals("SendRequestCmd"))
{
var clickedRow = ((Button)e.CommandSource).NamingContainer as GridViewRow;
// now access the cells like this
var clickedSLNo = clickedRow.cells[0].Text;
}
Update:
e.CommandSource definition
A instance of the System.Object class that represents the source of the command.
IButtonControl.CommandArgument definition
A control that implements the IButtonControl interface must implement the CommandArgument property and the CommandName property to indicate the argument and command name that are propagated to the Command event.

Related

How can I update all the data in a database specified by selected rows in Asp GridView with a button located outside of the GridView?

I looked for some similar questions, but found only ListView solutions
But I have a GridView and a button outside of the GridView and need to udate only records specified by a selected checkbox.
<asp:GridView ID="gvData"
runat="server" Width = "850px"
CellPadding="5"
AutoGenerateColumns="false"
AllowPaging ="true"
OnPageIndexChanging ="OnPaging" PageSize="5">
<HeaderStyle CssClass="HeaderStyle" />
<PagerStyle CssClass="HeaderStyle" HorizontalAlign="Center" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
<RowStyle CssClass="RowStyle" />
<RowStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField HeaderText="Id" ItemStyle-Width="20px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked = "false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Message" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblMessage" runat="server" Width="500px" Text='<%# Eval("Message") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="text-align:left;">
<asp:Button ID="btnChange" runat="server" Text="Change Type" OnClick="btnChange_Click" />
</div>
I have a method btnChange_Click():
protected void btnChange_Click()
{
int index = gvFailedMerchants.SelectedRow.RowIndex;
DbConnection.UpdateMessageType(index);
}
When I click the button, I'm getting the message
"Object reference not set to an instance of an object"
I want to write a logic that where I traverse the grid and add ids of the selected row into one string where all ids are separated by commas:
1,2,3,4,5
Then I will send this string to the stored procedure and use them in a query within IN close:
UPDATE MYTABLE SET column = myValue WHERE ID IN('1,2,3,4,5')
I do not know what is the right approach to the problem.
How can I do that?
Please try this,
<asp:TemplateField HeaderText="Select" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked = "false"
OnCheckedChanged="ChkSelect_CheckedChanged" data-id='<%# Eval("id") %>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
protected void ChkSelect_CheckedChanged(object sender, EventArgs e)
{
try
{
CheckBox chkSel = sender as CheckBox;
string id= chkSel.Attributes["data-id"].ToString();
if (chkSel.Checked == true)
{
Session["ID"] += (Session["ID"].ToString() == "" ? id: "," + id);
}
else
{
string existingCodes = Session["ID"].ToString();
Session["ID"] = existingCodes.Replace(id, "");
}
protected void btnChange_Click()
{
string ids = Session["ID"].ToString();
DbConnection.UpdateMessageType(ids);
}

ASP.net Gridview Row Deletion

I am using Visual Studio 2015 and Entity Framework 6. I have a gridview displaying orders from a database. However, I need a user to be able to click a row and be taken to another page for editing that row after a dialog box confirmation.
This is what I have:
<asp:GridView ID="gridOrders" runat="server" Height="184px" Width="1359px" AutoGenerateColumns="false"
AllowSorting="true" >
<HeaderStyle Font-Bold="true" Font-Size="16pt" BackColor="#cc0000" ForeColor="Black" />
<RowStyle Font-Size="12pt" BackColor="#afadad" ForeColor="White"/>
<AlternatingRowStyle BackColor="#afadad" ForeColor="White" />
<Columns>
<asp:CommandField HeaderText="" SelectText="CANCEL ORDER" ShowSelectButton="true" ControlStyle-ForeColor="White" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" SortExpression="FirstName" />
How do I make the row selection to another page happen with a dialog that asks user if they are sure?
Change your aspx page with the below code
<asp:GridView ID="gridOrders" runat="server" Height="184px" Width="1359px" AutoGenerateColumns="False"
AllowSorting="True">
<HeaderStyle Font-Bold="true" Font-Size="16pt" BackColor="#cc0000" ForeColor="Black" />
<RowStyle Font-Size="12pt" BackColor="#afadad" ForeColor="White" />
<AlternatingRowStyle BackColor="#afadad" ForeColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lnkCancelOrder" runat="server" OnClientClick="return confirm('Are you sure to redirect?')" OnClick="lnkCancelOrder_Click" CausesValidation="False" CommandArgument='<%#Eval("OrderID") %>' CommandName="Select" Text="CANCEL ORDER"></asp:LinkButton>
</ItemTemplate>
<ControlStyle ForeColor="White" />
</asp:TemplateField>
<asp:BoundField HeaderText="First Name" DataField="FirstName" SortExpression="FirstName" />
</Columns>
</asp:GridView>
Write the c# code as follows
You can redirect to another page and pass the orderID as QueryString, and retrieve the complete order information by orderID and show that in an edit mode form
protected void lnkCancelOrder_Click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
string orderID = lnk.CommandArgument;
Response.Redirect("AnotherPage.aspx?orderId="+orderID);
}
Write under the <asp:TemplateField> of Gridview as
<asp:LinkButton ID="anchrTag" runat="server" PostBackUrl="Your edit page url" OnClientClick="return confirm('Are u sure to leave this page and want to go for edit?');">Edit</asp:LinkButton>

How to update a label out of gridview by TemplateField checkbox in that gridview without postback

I have a gridview and every row has a checkbox at first column. I bind datagridview to a datasource of bills. I want to display the sum of the bills' that is checked on a label which is out of the gridview. And also i don't want the checkbox do postback. I try to do this with javascript(onclick event of asp:checkbox) but couldn't achieved. I also try AjaxControlToolkit but again unsuccess.
Please help.
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False" Width="100%"
CssClass="gv">
<Columns>
<asp:TemplateField HeaderText="Seç" HeaderStyle-Width="50px">
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" Checked="false"/>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="InvoiceDate" HeaderText="Fatura Tarihi" DataFormatString="{0:dd-MM-yyyy}">
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Amount" HeaderText="Tutar" DataFormatString="{0:N2} TL">
<HeaderStyle HorizontalAlign="Right" />
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
</Columns>
</asp:GridView>
As you have mentioned, you have also tried JS for your solution. so here i am posting your solution in JS.
i supposed your label id lbl (where you want to show the sum of corresponding column name Tutar ).
your label
<asp:Label ID="lbl" runat="server"></asp:Label>
you just need to add a class to your checkbox. i used mychk.
so your code for checkbox would be like this
Columns>
<asp:TemplateField HeaderText="Seç" HeaderStyle-Width="50px">
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" Checked="false" class="mychk" />
</ItemTemplate>
</asp:TemplateField>
and your jquery would be
<script type="text/javascript">
$(document).ready(function () {
var sum = parseInt($('#lbl').html()) || 0;
$('.mychk input[type="checkbox"]').on('change', function () {
if ($(this).is(':checked')) {
sum += parseInt($(this).closest('tr').find('td:eq(2)').html()) || 0;
} else {
sum -= parseInt($(this).closest('tr').find('td:eq(2)').html()) || 0;
}
$('#lbl').html(sum);
});
});
</script>
it will show you sum when you check or uncheck the checkboxes

Hidden field in detailsview - aspnet membership userID

I have a little detailsview where i can add some data to my DB.
The detailsview's code:
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
DataSourceID="orderSqlDataSource" DefaultMode="Insert" Height="50px"
Width="333px" DataKeyNames="ID" CellPadding="4" ForeColor="#333333"
GridLines="None" oniteminserted="DetailsView1_ItemInserted"
onprerender="DetailsView1_PreRender">
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
<EditRowStyle BackColor="#E9ECF1" />
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
<Fields>
<asp:BoundField DataField="userid" HeaderText="Azonosító"
SortExpression="userid" ReadOnly="True" />
<asp:BoundField DataField="quantity" HeaderText="Mennyiség (kg)"
SortExpression="quantity" />
<asp:TemplateField HeaderText="Mit rendel" SortExpression="Mit rendel">
<InsertItemTemplate>
<asp:DropDownList ID="ordertypeDropDownList" runat="server"
DataSourceID="ordertypeDDLSqlDataSource" DataTextField="name"
DataSource='<%# Bind("ordertype") %>'
SelectedValue='<%# Bind("ordertype") %>'
DataValueField="ID">
</asp:DropDownList>
<asp:SqlDataSource ID="ordertypeDDLSqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:dotnetConnectionString %>"
SelectCommand="SELECT [name], [ID] FROM [product]"></asp:SqlDataSource>
</InsertItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowInsertButton="True" CancelText="Mégsem"
InsertText="Elküld" />
</Fields>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
</asp:DetailsView>
Here is the code behind for the page_load event:
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
MembershipUser user = Membership.GetUser(User.Identity.Name);
string userID = user.ProviderUserKey.ToString();
((TextBox)DetailsView1.Rows[0].Cells[1].Controls[0]).Text = userID;
}
}
As you can see i fill the first boundfield from the page_load.
The problem is that the first boundfield (userid, or in my native language "azonosító") is important because of the database, but i don't want to let the user see his/her userid.
If i make the boundfield hidden (visible=false), it won't be reachable with the code in the page_load.
How can i bound the current userID to that field, when the field is hidden, or how can i get this work without boundfield for the ID?
Thanks in advance!
If the user doesn't need to know or interact with the value you are inserting, then it is quite easy to inject parameter values into the insert call that the DetailsView sends to your datasource control. Just use the DetailsView.Inserting event DetailsViewInsertEventArgs parameter as shown.
Code:
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
if (User.Identity.IsAuthenticated)
{
MembershipUser user = Membership.GetUser(User.Identity.Name);
string userID = user.ProviderUserKey.ToString();
e.Values.Add("userid", userID);
}
}
As you might expect, this method makes the BoundField completely unnecessary :)
Use Template Field and place a label and bind it with userid. You can access the label in your codebehind irrespective of it is invisible.
<asp:DetailsView runat="server" ID="dv" >
<Fields>
<asp:TemplateField Visible="false" >
<ItemTemplate>
<asp:Label ID="lb" runat="server" Text='<%# Bind("userid") %>' />
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
// In your code behind
string userid = ((Label)dv.Rows[0].FindControl("lb")).Text(); // give the correct index

How to redirect an asp page to 2 other pages?

I have a web page with checkbox list to choose multiple crystal reports to view. I want to open these reports in new tabs or windows.
I tried this :
This is the show report button:
<asp:Button ID="Button2" runat="server" Text="Show Report" OnClick="ButtonShowReport_Click"
CssClass="button" OnClientClick="aspnetForm.target ='_blank';"/>
And this is my gridview control:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
RowStyle-HorizontalAlign="Center" AutoGenerateColumns="False"
DataKeyNames="AccountID">
<RowStyle BackColor="#>
<Columns>
<asp:TemplateField HeaderText="Choose Client's Accounts">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label id="lblAccountId" runat ="server" text='<%# Eval("AccountID")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="AccountID" HeaderText="AccountID" Visible="false"/>
<asp:BoundField DataField="AccountName" HeaderText="Account Name" />
<asp:BoundField DataField="Name" HeaderText="Client Name" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
My c# code looks like:
protected void ButtonShowReport_Click(object sender, EventArgs e)
{
string accountID;
int Rows = GridView1.Rows.Count;
for (int i = 0; i < Rows; i++)
{
//CheckBoxField cb = ((CheckBoxField)gvASH.Rows[i].Cells[1]).;
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
if (cb.Checked == true)
{
accountID = ((Label)GridView1.Rows[i].FindControl("lblAccountID")).Text;//GridView1.DataKeys[i].Value.ToString();//GridView1.Rows[i].Cells[1].Text;
//Button2.Enabled = true;
openReport(accountID);
}
}
}
protected void openReport(string accountID)
{
//some code for setting parameters of the crystal report
//and for creating report key
Response.Redirect(string.Format("~/Report.aspx?ReportKey={0}",
ReportKey.ToString()),false);
}
So if the user checked 2 reports and clicked on the ShowReport button, it'll do the loop but opens only one new tab with the last report chosen ...
Any Suggestions please ??
Add this to the control which triggers the redirect. I know this works for Buttons/LinkButtons, not sure if it will work on a checkbox though.
OnClientClick="aspnetForm.target ='_blank';"
One method you might consider:
Instead of doing the Redirect to each report inside the code behind - dynamically generate some JavaScript that has uses window.open for each report. The javascript would look similar to this:
<script type="text/javascript">
window.open("<report1URL>", "_blank");
window.open("<report2URL>", "_blank");
...
window.open("<reportNURL>", "_blank");
</script>
Then, instead of doing a Response.Redirect, you should be able to do a Respone.Write() to get the browser to execute the code.
string myJavaScript= <dynamicallyGenerateJavascript>;
Response.Write(myJavaScript);

Resources