Retrieving data from DetailsView - c#

I'm trying to retrieve data from the DetailsView control in order to input them into another database table. I've looked through other questions that others asked but none of their questions could fit into my situation, which is trying to access SQL Database. Ultimately, I couldn't find the answer I require.
Basically, my objective of the codes is to extract the second row of the DetailsView, since the first row are mostly the static headers that do not change. My DetailsView would change upon the selection of a GridView above. Hence, I'm trying to retrieve the data on the second row, explaining my usage of Rows[2] , while I presume that "Cells[]" refers to the columns.
I'm using the following codes to do so.
string insertQuery = "insert into SalesOrders ([pQuotation#], pServices, pQty, pDescription, [p[Price/Unit]], pNetvalue, pProgress, pClientNo values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con)
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text);
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text);
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text);
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text);
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text);
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text);
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
I've been thrown the following exception:
Error:System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index at System.Web.UI.ControlCollection.get_Item(Int32 index) at RealClientPurchase.Button1_Click(Object sender, EventArgs e) in d:\Desktop\RealClientPurchase.aspx.cs:line 27
EDIT:
This is the code behind file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class RealClientPurchase : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
clientnolbl.Text = Session["sClientNo"].ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;Integrated Security=True;Connect Timeout=30");
try
{
con.Open();
SqlCommand cmd;
string insertQuery = "insert into SalesOrders ([pQuotation#], pServices, pQty, pDescription, [p[Price/Unit]], pNetvalue, pProgress, pClientNo values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text);
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text);
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text);
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text);
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text);
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text);
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect",
"alert('Purchase order has been submitted! Kindly proceed to checkout.'); window.location='" +
Request.ApplicationPath + "CurrentCheckout.aspx';", true);
con.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}
These are the aspx codes:
<%# Page Title="" Language="C#" MasterPageFile="~/ClientPortal.master" AutoEventWireup="true" CodeFile="RealClientPurchase.aspx.cs" Inherits="RealClientPurchase" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Register1ConnectionString %>" SelectCommand="SELECT [qQuotationNo], [qServices], [qQuantity], [qDate] FROM [Quotations] WHERE ([qClientNo] = #qClientNo)">
<SelectParameters>
<asp:SessionParameter Name="qClientNo" SessionField="sClientNo" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:Register1ConnectionString %>" SelectCommand="SELECT [qQuotationNo], [qServices], [qQuantity], [qDescription], [qPricePerQty], [qTotalPayable] FROM [Quotations] WHERE ([qQuotationNo] = #qQuotationNo)">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="qQuotationNo" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Label ID="clientnolbl" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="qQuotationNo" DataSourceID="SqlDataSource1" Height="125px" Width="452px" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="qQuotationNo" HeaderText="Quotation No" InsertVisible="False" ReadOnly="True" SortExpression="qQuotationNo" />
<asp:BoundField DataField="qServices" HeaderText="Services" SortExpression="qServices" />
<asp:BoundField DataField="qQuantity" HeaderText="Quantity" SortExpression="qQuantity" />
<asp:BoundField DataField="qDate" HeaderText="Date" SortExpression="qDate" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSource2" Height="50px" Width="452px" CellPadding="4" ForeColor="#333333" GridLines="None" DataKeyNames="qQuotationNo">
<AlternatingRowStyle BackColor="White" />
<CommandRowStyle BackColor="#D1DDF1" Font-Bold="True" />
<EditRowStyle BackColor="#2461BF" />
<FieldHeaderStyle BackColor="#DEE8F5" Font-Bold="True" />
<Fields>
<asp:BoundField DataField="qQuotationNo" HeaderText="qQuotationNo" SortExpression="qQuotationNo" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="qServices" HeaderText="qServices" ReadOnly="True" SortExpression="qServices" />
<asp:BoundField DataField="qQuantity" HeaderText="qQuantity" SortExpression="qQuantity" ReadOnly="True" />
<asp:BoundField DataField="qDescription" HeaderText="qDescription" SortExpression="qDescription" ReadOnly="True" />
<asp:BoundField DataField="qPricePerQty" HeaderText="qPricePerQty" SortExpression="qPricePerQty" ReadOnly="True" />
<asp:BoundField DataField="qTotalPayable" HeaderText="qTotalPayable" SortExpression="qTotalPayable" ReadOnly="True" />
</Fields>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
</asp:DetailsView>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
<br />
<br />
<br />
</asp:Content>

I've found the solution.
I changed the fields in the database table to exclude "#" and "[" or "]"
It appears these signs do not function well in a SQL statement.
Revamped codes are as follows, and they do work.
SqlCommand cmd;
string insertQuery = "INSERT INTO SalesOrders (pQuotationNo, pServices, pQty, pDescription, pPricePerQty, pNetvalue, pProgress, pClientNo) values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
cmd.ExecuteNonQuery();

Can you try DetailsView1.Rows[0].Cells[0].Text?
Since your DetailsView has BoundFields only, this should work.
Regards

Related

Gridview Delete Link returns "[ERROR] : Deleting is not supported by data source 'SqlDataSource1' unless DeleteCommand is specified."

I have a reservation system and I am having a problem with my delete link that is inside my gridview that is supposedly to delete temporarily reserved rooms, it returns an error page stating that "Deleting is not supported by data source 'SqlDataSource1' unless DeleteCommand is specified." but when I relog-in the account I used the data was removed. Here is my code
ASP.net
<asp:GridView ID="cartGView" runat="server" DataKeyNames="ROOM_ID" AutoGenerateColumns="False" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" Width="100%" DataSourceID="SqlDataSource1" GridLines="Horizontal" OnRowDeleting="cartGView_RowDeleting">
<RowStyle HorizontalAlign ="Center" />
<Columns>
<asp:CommandField SelectText="Delete" ShowDeleteButton="True" />
<asp:BoundField DataField="ROOM_ID" HeaderText="Room ID" SortExpression="ROOM_ID" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="ROOM_TYPE" HeaderText="Room Type" SortExpression="ROOM_TYPE" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="NO_GUEST" HeaderText="Guest" SortExpression="NO_GUEST" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="PRICE" HeaderText="Price" SortExpression="PRICE" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="SUB_PRICE" HeaderText="Sub Price" SortExpression="SUB_PRICE" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
</Columns>
<EmptyDataTemplate>
<br></br><center>Select Room</center>
<br></br>
</EmptyDataTemplate>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Bakasyunan %>" SelectCommand="SELECT DISTINCT [ROOM_ID], [ROOM_TYPE], [PRICE], [SUB_PRICE], [NO_GUEST] FROM [TBL_MyCart] WHERE ([USERNAME] = #USERNAME)" OnSelecting="SqlDataSource1_Selecting">
<SelectParameters>
<asp:SessionParameter Name="USERNAME" SessionField="username" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
C#:
protected void cartGView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
string roomid = Convert.ToString(cartGView.DataKeys[e.RowIndex].Values[0]);
cd.DeleteRecordWalkCart(roomid);
cartGView.DataSourceID = "SqlDataSource1";
cartGView.DataBind();
if (cartGView.Rows.Count == 0)
{
subtotalBox.Text = "P 0.00";
continueBtn.Enabled = false;
continueBtn.BackColor = System.Drawing.ColorTranslator.FromHtml("#2C2A2A");
}
else if (cartGView.Rows.Count > 0)
{
SqlCommand sumcmd = new SqlCommand("SELECT SUM(SUB_PRICE) FROM TBL_MyCart", conn); //<-- Add Subtotal
conn.Open();
string sum = sumcmd.ExecuteScalar().ToString();
conn.Close();
subtotalBox.Text = "P " + sum + ".00";
continueBtn.Enabled = true;
continueBtn.BackColor = System.Drawing.ColorTranslator.FromHtml("#6c0404");
}
}
catch(Exception ex)
{
Label1.Text = ex.Message;
}
}
Any help will be much appreciated! Thank you!

Editing a Bound Gridview Error

I'm implementing an "edit" feature on my Gridview bound to my "books" table. I'm receiving an error on RowEditingEvent wasn't handled. I don't understand where I'm going wrong or if I'm missing a reference somewhere but it seems to me that everything is handled.
public partial class AddEdit_Text_Books : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
string query = "select * from textBooks ";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["HUTDMSConnectionString"].ToString()))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
adapter.Fill(dt);
ViewState["allBooks"] = dt;
this.BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["allBooks"] as DataTable;
GridView1.DataBind();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string name = (row.Cells[0].Controls[0] as TextBox).Text;
string country = (row.Cells[1].Controls[0] as TextBox).Text;
DataTable dt = ViewState["allBooks"] as DataTable;
ViewState["allBooks"] = dt;
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnCancel(object sender, EventArgs e)
{
GridView1.EditIndex = -1;
this.BindGrid();
}
}
}
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="BookID" Width="1482px" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="thirteenISBN" HeaderText="thirteenISBN" SortExpression="thirteenISBN" />
<asp:BoundField DataField="CourseID" HeaderText="CourseID" SortExpression="CourseID" />
<asp:BoundField DataField="BookTitle" HeaderText="BookTitle" SortExpression="BookTitle" />
<asp:BoundField DataField="Ancillary" HeaderText="Ancillary" SortExpression="Ancillary" />
<asp:BoundField DataField="BookActive" HeaderText="BookActive" SortExpression="BookActive" />
<asp:BoundField DataField="ActiveDate" HeaderText="ActiveDate" SortExpression="ActiveDate" />
<asp:BoundField DataField="InactiveDate" HeaderText="InactiveDate" SortExpression="InactiveDate" />
<asp:BoundField DataField="Author" HeaderText="Author" SortExpression="Author" />
<asp:BoundField DataField="BookID" HeaderText="BookID" InsertVisible="False" ReadOnly="True" SortExpression="BookID" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="eISBN" HeaderText="eISBN" SortExpression="eISBN" />
<asp:BoundField DataField="ebookAvailable" HeaderText="ebookAvailable" SortExpression="ebookAvailable" />
<asp:BoundField DataField="VendorISBN" HeaderText="VendorISBN" SortExpression="VendorISBN" />
<asp:BoundField DataField="tenISBN" HeaderText="tenISBN" SortExpression="tenISBN" />
<asp:BoundField DataField="EditionAndDate" HeaderText="EditionAndDate" SortExpression="EditionAndDate" />
<asp:BoundField DataField="Publisher" HeaderText="Publisher" SortExpression="Publisher" />
<asp:BoundField DataField="Imprint" HeaderText="Imprint" SortExpression="Imprint" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton Text="Update" runat="server" OnClick="OnUpdate" />
<asp:LinkButton Text="Cancel" runat="server" OnClick="OnCancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<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" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HUTDMSConnectionString %>" SelectCommand="SELECT [thirteenISBN], [CourseID], [BookTitle], [Ancillary], [BookActive], [ActiveDate], [InactiveDate], [Author], [BookID], [Notes], [eISBN], [ebookAvailable], [VendorISBN], [tenISBN], [EditionAndDate], [Publisher], [Imprint] FROM [textBooks]"></asp:SqlDataSource>
You have not registered onediting event in gridview definition.
Add OnRowEditing ="OnRowEditing" in below gridview definition.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="BookID" Width="1482px"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowEditing ="OnRowEditing">

how to navigate to a url using linkbutton in gridview

i have a gridview which stores names of software and a button field. What i want to do is that by executing a query behind "open" linkbutton and the resulting answer which is a url from database, i want to navigate to that link which is stored in the variable.
e.g: when i click open button i want to navigate to "www.google.com"
so far what i have coded is:
<asp:GridView ID="GridView2" runat="server" ShowHeaderWhenEmpty="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" DataSourceID="softwares" ForeColor="Black" GridLines="Vertical" OnRowCommand="GridView2_RowCommand">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="Softwares" HeaderText="Softwares" SortExpression="Softwares" />
<asp:ButtonField CommandName="open" Text="Open" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
<asp:SqlDataSource ID="softwares" runat="server" ConnectionString="<%$ ConnectionStrings:certConnectionString %>" SelectCommand="SELECT sw_name AS Softwares FROM Software"></asp:SqlDataSource>
C# code:
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "open")
{
using(CertDataContext context=new CertDataContext())
{
int i=Convert.ToInt32(e.CommandArgument);
var open = (from a in context.Softwares where a.sw_name == GridView2.Rows[i].Cells[0].Text select a).FirstOrDefault();
Response.Redirect(open.tosting());
}
}
}
HttpResponse.Redirect(string)
The parameter CAN be an absolute url. Check the example Microsoft gives in their documentation.

Error getting values from row on 'delete' clicked in GridView

I am getting this error while I click on the delete button
System.ArgumentOutOfRangeException:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
And the GridView3_RowDeleting is as follows
protected void GridView3_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label1.Text = GridView3.DataKeys[e.RowIndex].Value.ToString();
}
How can I access values of that particular row?
<asp:GridView ID="GridView3" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" HorizontalAlign="Left" Width="16px" Height="5px" PageSize="5" OnRowDeleting="GridView3_RowDeleting" OnSelectedIndexChanged="GridView3_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="DName" HeaderText="DName" SortExpression="DName" />
<asp:BoundField DataField="bloodGroup" HeaderText="Group" SortExpression="bloodGroup" />
<asp:BoundField DataField="contact_number" HeaderText="Contact#" SortExpression="contact_number" />
<asp:BoundField DataField="dateDonated" HeaderText="dateDonated" SortExpression="dateDonated" />
<asp:BoundField DataField="city" HeaderText="city" SortExpression="city" />
<asp:BoundField DataField="arid_number" HeaderText="Arid#" SortExpression="arid_number" />
<asp:CommandField ShowDeleteButton="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>
you are missing *DataKeyNames * attribute in Gridview.
<asp:GridView DataKeyNames ="yourID"---------------------------------------->
if you use "DName" as your DataKeyNames like <asp:GridView DataKeyNames="DName" then you get column DName value of your deleting row in label
Label1.Text = GridView3.DataKeys[e.RowIndex].Value.ToString();
Label1.Text=(value of DName of your row thats deleting)
Following is a working example: May helpful
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductDesc" HeaderText="ProductDesc" SortExpression="ProductDesc" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthWindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductDesc] FROM [Product]"
DeleteCommand="DELETE FROM [Product] WHERE [ProductID] = #ProductID" >
<DeleteParameters>
<asp:Parameter Name="ProductID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
Here ProductID is uniqueKey using in DataKeyNames and in Deleting a record, while in your case DID...
Following should be your code...Enjoy
<asp:GridView DataKeyNames="DID" ID="GridView3" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" HorizontalAlign="Left" Width="16px"
Height="5px" PageSize="5" OnRowDeleting="GridView3_RowDeleting" OnSelectedIndexChanged="GridView3_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="DID" HeaderText="DID" SortExpression="DID" Visible="false" />
<asp:BoundField DataField="DName" HeaderText="DName" SortExpression="DName" />
<asp:BoundField DataField="bloodGroup" HeaderText="Group" SortExpression="bloodGroup" />
<asp:BoundField DataField="contact_number" HeaderText="Contact#" SortExpression="contact_number" />
<asp:BoundField DataField="dateDonated" HeaderText="dateDonated" SortExpression="dateDonated" />
<asp:BoundField DataField="city" HeaderText="city" SortExpression="city" />
<asp:BoundField DataField="arid_number" HeaderText="Arid#" SortExpression="arid_number" />
<asp:CommandField ShowDeleteButton="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>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
DeleteCommand="DELETE FROM [tblDonors] WHERE [DID]=#DID"
SelectCommand="SELECT [DName], [gender], [bloodGroup], [contact_number], [city], [arid_number], [avallibilityTime], [dateDonated], [email] FROM [tblDonors]">
<DeleteParameters>
<asp:Parameter Name="DID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>

delete a row from the gridview from .cs

This is my aspx page
<asp:GridView ID="GridViews1" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None"
>
<Columns>
<asp:TemplateField HeaderText = "S.No">
<ItemTemplate>
<asp:Label ID="Sno" runat="server" Text= '<%#Eval("id")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Name">
<ItemTemplate >
<a href= "<%# Eval("Photo") %>" > <%# Eval("name") %> </a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Photo">
<ItemTemplate>
<img src='<%# Eval("Photo") %>' alt='<%# Eval("Name") %>' height= "50px" width = "50px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<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" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
and this is my .cs file
public partial class people_db_mysql : System.Web.UI.Page
{
String MyConString = "SERVER=localhost;" +
"DATABASE=shortandsweet;" +
"UID=root;" +
"PASSWORD=;";
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(MyConString);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM people_details;", conn);
conn.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridViews1.DataSource = dataTable;
GridViews1.DataBind();
}}
now the output i get is
[ S.NO, Name , Photo , sno, name and photo ]
the first three fields are from the aspx page which i want it to be displayed and i dont want the other 3 fields to be displayed any ideas how i might achieve that ?
and moreover ive tried this
GridViews1.Columns[3or4or5].Visible = false; //and it says array out of bounds
however i can hide the 0,1,2 fields with the same command, is there a way to hide the rows generated through the .cs files ?
if i try to limit the rows through the select query it doesnt display anything, i just get a blank screen.
The Gridview control has a property 'AutoGenerateColumns' which has to be set to 'false', otherwise it will autogenerate the columns, even if you have manually added them.
<asp:GridView ID="GridViews1" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="false"
>

Categories

Resources