void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow grvrow = e.Row;
Table tbl = new Table();
TableRow row = new TableRow();
TableCell[] aTD = new TableCell[grvrow.Cells.Count];
grvrow.Cells.CopyTo(aTD, 0);
grvrow.Cells.Clear();
row.Cells.AddRange(aTD);
tbl.Rows.Add(row);
//second row
row = new TableRow();
TableCell cell = new TableCell();
cell.ColumnSpan = aTD.Length;
row.Cells.Add(cell);
cell.Text = "This line contains a new header line that was added while handling the databound event to manipulate the header row";
cell.CssClass = "Header";
cell.BorderColor = System.Drawing.Color.BurlyWood;
tbl.Rows.Add(row);
//create a new cell within the gridview row
TableCell cellGRV = new TableCell();
cellGRV.ColumnSpan = aTD.Length;
grvrow.Cells.Add(cellGRV);
cellGRV.Controls.Add(tbl);
}
}
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<div style="width: 750px;">
<h2>
Parent-Child GridViews using show/hide rows within the same table</h2>
<p>
Click on the arrow icon in front of a record to toggle the view between detail and
summary.</p>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
DataKeyNames="CustomerID" DataSourceID="sqldsCustomers" AutoGenerateColumns="False"
OnRowCommand ="GridView1_RowCommand"
CssClass="NestedGridView1Style" OnRowCreated ="GridView1_RowCreated">
<SelectedRowStyle CssClass="Green" />
<HeaderStyle CssClass="Pink" />
<Columns>
<asp:ButtonField ButtonType="Image" ImageUrl="~/images/arrow.gif" CommandName="Select"
Text="Click here to toggle the display of the orders list for this customer" />
<asp:TemplateField>
<HeaderTemplate>
<table cellpadding="2" cellspacing="0" border="0" width="510px">
<!-- this row has the parent grid -->
<tr>
<td width="300px">
Company Name</td>
<td width="100px">
City</td>
<td width="100px">
Country</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table border="0" cellpadding="2" cellspacing="0" width="510">
<!-- this row has the parent grid -->
<tr>
<td width="300">
<asp:Label ID="lblCompanyName" runat="server" Text='<%# Eval("CompanyName") %>'></asp:Label>
</td>
<td width="100">
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
</td>
<td width="100">
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</td>
</tr>
<!-- this row has the child grid and its details view-->
<tr>
<td colspan="3">
<table border="0" cellpadding="3" cellspacing="0" width="100%">
<tr>
<!-- this cell has the list of orders for the selected customer -->
<td>
<asp:GridView ID="ChildGridView1" runat="server" DataKeyNames="OrderID" Visible="False"
OnRowCommand="ChildGridView_RowCommand"
DataSourceID="SqldsOrders" AutoGenerateColumns="False" CssClass="GridView1ChildStyle"
OnSelectedIndexChanged="ChildGridView1_SelectedIndexChanged">
<SelectedRowStyle CssClass="Blue" />
<HeaderStyle CssClass="Header" />
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="Order Date">
<EditItemTemplate>
<asp:TextBox ID="txtOrderDate" runat="server" Text='<%# Bind("OrderDate", "{0:d}") %>'
Width="70px"></asp:TextBox>
<asp:CompareValidator ID="valComp1" ValueToCompare="01/01/2020" ControlToValidate="txtOrderDate"
Operator="LessThan" Type="Date" runat="server" Display="None" ErrorMessage="A valid date must be before January 01 2020" />
<asp:CompareValidator ID="valComp2" ValueToCompare="01/01/1980" ControlToValidate="txtOrderDate"
Operator="GreaterThan" Type="Date" runat="server" Display="None" ErrorMessage="Invalid Date: A valid date must be after January 01 1980" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("OrderDate", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shipped Date">
<EditItemTemplate>
<asp:TextBox ID="txtShippedDate" runat="server" Text='<%# Bind("ShippedDate", "{0:d}") %>'
Width="70px"></asp:TextBox>
<asp:CompareValidator ID="valComp3" ValueToCompare="01/01/2020" ControlToValidate="txtShippedDate"
Operator="LessThan" Type="Date" runat="server" Display="None" ErrorMessage="A valid date must be before January 01 2020" />
<asp:CompareValidator ID="valComp4" ValueToCompare="01/01/1980" ControlToValidate="txtShippedDate"
Operator="GreaterThan" Type="Date" runat="server" Display="None" ErrorMessage="Invalid Date: A valid date must be after January 01 1980" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("ShippedDate", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ship Name">
<EditItemTemplate>
<asp:TextBox ID="txtShipName" runat="server" Text='<%# Bind("ShipName") %>' Width="150px"
MaxLength="35"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("ShipName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Freight">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Freight", "{0:c}") %>'
Width="70px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Freight", "{0:c}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Image" ImageUrl="~/images/arrow.gif" CommandName="Select"
Text="Click here to toggle the display of the detailed products on this order" />
</Columns>
</asp:GridView>
</td>
<!--This cell has the order detail -->
<td>
<asp:DetailsView ID="detvOrder" runat="server" DataSourceID="sqldsOrderDetail" AllowPaging="True"
thanks for your mail , i have seen that link i am not understand this two function in that customercls
pls send sample code for me because iam learning c# , it would really helpful for me if u send the code for this
public DataTable Fetch()
{
// Write your own Fetch statement blocks, this method should return a DataTable
}
public DataTable FetchCustomerType()
{
// Write your own Fetch statement blocks to fetch Customer Type from its master table and this method should return a DataTable
}
Public dataTable Fetch() is a Method/Function where you manipulate data from your DB, Its basically a methods that returns a DataTable sothat it can be instantiated in your page.
For more details you can refer to this thread and find my post out there.. i have posted there of what you need to know
Have you read on the thread that i have posted before? Anyway
First you need to configure your connection string, so i would suggest to add your connection string in your Web Config file
Add this codes in Web Config file
<appSettings>
<add key="ConnString" value="Data Source=<Server Name>;Initial Catalog=<Name of Database>;Integrated Security=SSPI;"/>
</appSettings>
Second you need to create a method for fetching the data from your DB under your
customercls Class
Public Class customercls
{
public DataTable GetAllCustomers() // Returns a DataTable but you can also use DataSet
{
DataTable dt = new DataTable();
string sql = string.Empty;
try
{
sql = "SELECT * FROM tblCustomers ";// But i would suggest to use Stored Procedure for security purpose
DAL dal = new DAL(); // instantiate the DAL class to give access to the methods under it
dt = dal.FetchData(sql); // CALLS THE IFetchData Methods in the DAL Class
public DataTable GetCustomerType(string type) // Returns a DataTable with the parameter type but you can also use DataSet
{
DataTable dt = new DataTable();
string sql = string.Empty;
try
{
sql = "SELECT * FROM tblCustomers WHERE Type = ' " +type+ " ' ";//
But i would suggest to use Stored Procedure for security purpose
DAL dal = new DAL(); // instantiate the DAL class to give access to the methods under it
dt = dal.FetchData(sql); // CALLS THE FetchData() Methods in the DAL Class with the string parameter
Second Create a separate class that contains your DAL (Data Access Layer)
Public Class DAL
{
public void FetchData(string statements) //
{
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnString"]) // calling up your connection string that was configured earlier in you Web Config File
{
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(statement, conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//Do something here for catching errors
}
finally
{
conn.Close();
}
}
}
In your page you can now access this by calling the Class customercls, lets say you want to populate your grid based on the data retured in the GetAllCustomers() method
Kannandesika...
Member
368 Points
764 Posts
girdview insert,update,delete in c# using code
Dec 05, 2007 08:52 AM|LINK
Hi,
I wants to insert,delete,update in a grid and also insert image in a gridview can
we have any link for that i want to wite this in a codebehind.
Kannandesikan
jagjot
Contributor
2648 Points
1229 Posts
Re: girdview insert,update,delete in c# using code
Dec 05, 2007 09:24 AM|LINK
i think this is what you are after.
http://www.webswapp.com/codesamples/aspnet20/nestedgridviews/default.aspx
M.Sc, MIEEE, MCP, CCNA
vinz
All-Star
126946 Points
17922 Posts
MVP
Re: girdview insert,update,delete in c# using code
Dec 05, 2007 09:33 AM|LINK
Have a read on this article
http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx
This might help you
MessageBox Controls for WebForms | Blog | Twitter | Linkedin
Kannandesika...
Member
368 Points
764 Posts
Re: girdview insert,update,delete in c# using code
Dec 05, 2007 09:35 AM|LINK
Hi Jagjot,
thanks for your mail
i din't get your link, send sample code for this.
Kannandesikan
jagjot
Contributor
2648 Points
1229 Posts
Re: girdview insert,update,delete in c# using code
Dec 05, 2007 09:51 AM|LINK
<%@ Import Namespace="System.Data" %>
<%@ Page Language="C#" AutoEventWireup="false" Theme="WEBSWAPP" MasterPageFile="~/Webswapp.master" %>
<script language="C#" runat="server">
void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView gv = (GridView)sender;
Int32 rowIndex = Convert.ToInt32(e.CommandArgument.ToString());
switch (e.CommandName)
{
case "Select":
GridView childgv = (GridView)gv.Rows[rowIndex].FindControl("ChildGridView1");
if (childgv != null)
{
childgv.Visible = !childgv.Visible;
SqlDataSource SqldsOrders = (SqlDataSource)gv.Rows [rowIndex].FindControl("SqldsOrders");
SqldsOrders.SelectParameters["CustomerID"].DefaultValue = gv.DataKeys[rowIndex][0].ToString ();
DetailsView detV = (DetailsView)gv.Rows[rowIndex].FindControl("detvOrder");
if (detV != null) detV.Visible = childgv.Visible;
}
break;
}
}
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow grvrow = e.Row;
Table tbl = new Table();
TableRow row = new TableRow();
TableCell[] aTD = new TableCell[grvrow.Cells.Count];
grvrow.Cells.CopyTo(aTD, 0);
grvrow.Cells.Clear();
row.Cells.AddRange(aTD);
tbl.Rows.Add(row);
//second row
row = new TableRow();
TableCell cell = new TableCell();
cell.ColumnSpan = aTD.Length;
row.Cells.Add(cell);
cell.Text = "This line contains a new header line that was added while handling the databound event to manipulate the header row";
cell.CssClass = "Header";
cell.BorderColor = System.Drawing.Color.BurlyWood;
tbl.Rows.Add(row);
//create a new cell within the gridview row
TableCell cellGRV = new TableCell();
cellGRV.ColumnSpan = aTD.Length;
grvrow.Cells.Add(cellGRV);
cellGRV.Controls.Add(tbl);
}
}
void ChildGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView gv = (GridView)sender;
Int32 rowIndex = Convert.ToInt32(e.CommandArgument.ToString());
switch (e.CommandName)
{
case "Select":
DetailsView detV = (DetailsView)gv.Parent.FindControl("detvOrder");
if (detV != null)
{
SqlDataSource SqldsOrders = (SqlDataSource)gv.Parent.FindControl("sqldsOrderDetail");
SqldsOrders.SelectParameters["OrderId"].DefaultValue = gv.DataKeys[rowIndex][0].ToString();
}
break;
}
}
protected void ChildGridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.SelectedRow.FindControl("detvOrder").Visible = !GridView1.SelectedRow.FindControl("detvOrder").Visible;
}
</script>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<div style="width: 750px;">
<h2>
Parent-Child GridViews using show/hide rows within the same table</h2>
<p>
Click on the arrow icon in front of a record to toggle the view between detail and
summary.</p>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
DataKeyNames="CustomerID" DataSourceID="sqldsCustomers" AutoGenerateColumns="False"
OnRowCommand ="GridView1_RowCommand"
CssClass="NestedGridView1Style" OnRowCreated ="GridView1_RowCreated">
<SelectedRowStyle CssClass="Green" />
<HeaderStyle CssClass="Pink" />
<Columns>
<asp:ButtonField ButtonType="Image" ImageUrl="~/images/arrow.gif" CommandName="Select"
Text="Click here to toggle the display of the orders list for this customer" />
<asp:TemplateField>
<HeaderTemplate>
<table cellpadding="2" cellspacing="0" border="0" width="510px">
<!-- this row has the parent grid -->
<tr>
<td width="300px">
Company Name</td>
<td width="100px">
City</td>
<td width="100px">
Country</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table border="0" cellpadding="2" cellspacing="0" width="510">
<!-- this row has the parent grid -->
<tr>
<td width="300">
<asp:Label ID="lblCompanyName" runat="server" Text='<%# Eval("CompanyName") %>'></asp:Label>
</td>
<td width="100">
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
</td>
<td width="100">
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</td>
</tr>
<!-- this row has the child grid and its details view-->
<tr>
<td colspan="3">
<table border="0" cellpadding="3" cellspacing="0" width="100%">
<tr>
<!-- this cell has the list of orders for the selected customer -->
<td>
<asp:GridView ID="ChildGridView1" runat="server" DataKeyNames="OrderID" Visible="False"
OnRowCommand="ChildGridView_RowCommand"
DataSourceID="SqldsOrders" AutoGenerateColumns="False" CssClass="GridView1ChildStyle"
OnSelectedIndexChanged="ChildGridView1_SelectedIndexChanged">
<SelectedRowStyle CssClass="Blue" />
<HeaderStyle CssClass="Header" />
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="Order Date">
<EditItemTemplate>
<asp:TextBox ID="txtOrderDate" runat="server" Text='<%# Bind("OrderDate", "{0:d}") %>'
Width="70px"></asp:TextBox>
<asp:CompareValidator ID="valComp1" ValueToCompare="01/01/2020" ControlToValidate="txtOrderDate"
Operator="LessThan" Type="Date" runat="server" Display="None" ErrorMessage="A valid date must be before January 01 2020" />
<asp:CompareValidator ID="valComp2" ValueToCompare="01/01/1980" ControlToValidate="txtOrderDate"
Operator="GreaterThan" Type="Date" runat="server" Display="None" ErrorMessage="Invalid Date: A valid date must be after January 01 1980" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("OrderDate", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shipped Date">
<EditItemTemplate>
<asp:TextBox ID="txtShippedDate" runat="server" Text='<%# Bind("ShippedDate", "{0:d}") %>'
Width="70px"></asp:TextBox>
<asp:CompareValidator ID="valComp3" ValueToCompare="01/01/2020" ControlToValidate="txtShippedDate"
Operator="LessThan" Type="Date" runat="server" Display="None" ErrorMessage="A valid date must be before January 01 2020" />
<asp:CompareValidator ID="valComp4" ValueToCompare="01/01/1980" ControlToValidate="txtShippedDate"
Operator="GreaterThan" Type="Date" runat="server" Display="None" ErrorMessage="Invalid Date: A valid date must be after January 01 1980" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("ShippedDate", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ship Name">
<EditItemTemplate>
<asp:TextBox ID="txtShipName" runat="server" Text='<%# Bind("ShipName") %>' Width="150px"
MaxLength="35"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("ShipName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Freight">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Freight", "{0:c}") %>'
Width="70px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Freight", "{0:c}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Image" ImageUrl="~/images/arrow.gif" CommandName="Select"
Text="Click here to toggle the display of the detailed products on this order" />
</Columns>
</asp:GridView>
</td>
<!--This cell has the order detail -->
<td>
<asp:DetailsView ID="detvOrder" runat="server" DataSourceID="sqldsOrderDetail" AllowPaging="True"
DataKeyNames="OrderID,ProductID" AutoGenerateRows="False">
<FieldHeaderStyle CssClass="DetailsView1Header" />
<HeaderStyle CssClass="Header" />
<HeaderTemplate>
<p>
Order Details</p>
</HeaderTemplate>
<Fields>
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="UnitPrice" HeaderText="Unit Price" DataFormatString="{0:c}"
HtmlEncode="False" />
<asp:BoundField DataField="Quantity" HeaderText="Quantity" DataFormatString="{0:#}"
HtmlEncode="False" />
<asp:BoundField DataField="Discount" HeaderText="Discount" DataFormatString="{0:c}"
HtmlEncode="False" />
<asp:BoundField DataField="ExtendedPrice" HeaderText="Extended Price" DataFormatString="{0:c}"
HtmlEncode="False" />
</Fields>
</asp:DetailsView>
</td>
</tr>
</table>
<asp:SqlDataSource ID="sqldsOrderDetail" runat="server" ConnectionString="<%$ ConnectionStrings:LoveYourEnemies %>"
SelectCommand="SELECT [Order Details].OrderID, [Order Details].ProductID, [Order Details].UnitPrice, [Order Details].Quantity, [Order Details].Discount, Products.ProductName, ([Order Details].UnitPrice- [Order Details].Discount) * [Order Details].Quantity AS ExtendedPrice FROM [Order Details] INNER JOIN Products ON [Order Details].ProductID = Products.ProductID WHERE ([Order Details].OrderID = @OrderID)">
<SelectParameters>
<asp:Parameter Name="OrderId" DefaultValue="0" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqldsOrders" runat="server" ConnectionString="<%$ ConnectionStrings:LoveYourEnemies %>"
SelectCommand="SELECT * FROM Orders Where CustomerID=@CustomerID " UpdateCommand="Update Orders Set OrderDate=@OrderDate, ShippedDate=@ShippedDate, ShipName=@ShipName, Freight=@Freight where OrderID=@OrderID">
<SelectParameters>
<asp:Parameter Name="CustomerID" DefaultValue="0" Type="string" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="OrderID" Type="Int32" />
<asp:Parameter Name="OrderDate" Type="DateTime" />
<asp:Parameter Name="ShippedDate" Type="DateTime" />
<asp:Parameter Name="ShipName" Type="String" />
<asp:Parameter Name="Freight" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqldsCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:LoveYourEnemies %>"
SelectCommand="SELECT * FROM Customers "></asp:SqlDataSource>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
</div>
</asp:Content>
M.Sc, MIEEE, MCP, CCNA
Kannandesika...
Member
368 Points
764 Posts
Re: girdview insert,update,delete in c# using code
Dec 12, 2007 04:36 AM|LINK
Hi,
Vanz
thanks for your mail , i have seen that link i am not understand this two function in that customercls
pls send sample code for me because iam learning c# , it would really helpful for me if u send the code for this
public DataTable Fetch()
{
// Write your own Fetch statement blocks, this method should return a DataTable
}
public DataTable FetchCustomerType()
{
// Write your own Fetch statement blocks to fetch Customer Type from its master table and this method should return a DataTable
}
Kannandesikan
vinz
All-Star
126946 Points
17922 Posts
MVP
Re: girdview insert,update,delete in c# using code
Dec 12, 2007 05:03 AM|LINK
Public dataTable Fetch() is a Method/Function where you manipulate data from your DB, Its basically a methods that returns a DataTable sothat it can be instantiated in your page.
For more details you can refer to this thread and find my post out there.. i have posted there of what you need to know
http://forums.asp.net/p/1187777/2031770.aspx#2031770
if you have any concern, then let me know
MessageBox Controls for WebForms | Blog | Twitter | Linkedin
Kannandesika...
Member
368 Points
764 Posts
Re: girdview insert,update,delete in c# using code
Dec 12, 2007 05:26 AM|LINK
Hi vinz,
thanks for your mail,
i have createdCustomer Table with 6 columns for Customer Code[Code], Name[Name], Gender[Gender], City[City], State[State] and Customer Type[Type],
for the datamanupulation i have created the class called customercls,below two methods i don't no how manuplate for the database pls help me
i working in a live project this my first project in my company, iam learning c# sharp on my own., pls send sample code for this two methods
public DataTable Fetch()
{
}
public DataTable FetchCustomerType()
{
}
Regards
Kannan.D
Kannandesikan
vinz
All-Star
126946 Points
17922 Posts
MVP
Re: girdview insert,update,delete in c# using code
Dec 12, 2007 05:47 AM|LINK
Hi Kannan,
Have you read on the thread that i have posted before? Anyway
First you need to configure your connection string, so i would suggest to add your connection string in your Web Config file
Add this codes in Web Config file
<appSettings>
<add key="ConnString" value="Data Source=<Server Name>;Initial Catalog=<Name of Database>;Integrated Security=SSPI;"/>
</appSettings>
Second you need to create a method for fetching the data from your DB under your customercls Class
Public Class customercls
{
public DataTable GetAllCustomers() // Returns a DataTable but you can also use DataSet
{
DataTable dt = new DataTable();
string sql = string.Empty;
try
{
sql = "SELECT * FROM tblCustomers ";// But i would suggest to use Stored Procedure for security purpose
DAL dal = new DAL(); // instantiate the DAL class to give access to the methods under it
dt = dal.FetchData(sql); // CALLS THE IFetchData Methods in the DAL Class
return dt;
}
catch (System.Exception ex)
{
//Do something
}
}
public DataTable GetCustomerType(string type) // Returns a DataTable with the parameter type but you can also use DataSet
{
DataTable dt = new DataTable();
string sql = string.Empty;
try
{
sql = "SELECT * FROM tblCustomers WHERE Type = ' " +type+ " ' ";// But i would suggest to use Stored Procedure for security purpose
DAL dal = new DAL(); // instantiate the DAL class to give access to the methods under it
dt = dal.FetchData(sql); // CALLS THE FetchData() Methods in the DAL Class with the string parameter
return dt;
}
catch (System.Exception ex)
{
//Do something
}
}
}
Second Create a separate class that contains your DAL (Data Access Layer)
Public Class DAL
{
public void FetchData(string statements) //
{
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnString"]) // calling up your connection string that was configured earlier in you Web Config File
{
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(statement, conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//Do something here for catching errors
}
finally
{
conn.Close();
}
}
}
In your page you can now access this by calling the Class customercls, lets say you want to populate your grid based on the data retured in the GetAllCustomers() method
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
customercls cust = new customercls ();// First Instantiates the Class customercls that contains your GetAllCustomers() method
DataTable dt = cust.GetAllCustomers();// setting the DataTable with the value returned in your GetAllCustomers()
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Hope this makes sense....
MessageBox Controls for WebForms | Blog | Twitter | Linkedin
Kannandesika...
Member
368 Points
764 Posts
Re: girdview insert,update,delete in c# using code
Dec 12, 2007 05:55 AM|LINK
Hi venz,
thank you very much,
i got your point, thanz for guiding me.
Regards
Kannan.D
Kannandesikan