Gridview edit, update, delete and select events - c#

I have a dropdownlist that is populated by the names of the tables in the database. Then when the admin chooses or clicks a table name. The gridview below is populated by the data in the table. The admin should be able to edit, update, delete and select. However the commands supplied by the gridview are not working. When you click edit it does not execute. Then when you click select it deletes. The commands have a mix up somewhere. So l changed the commands into templates so l can code them myself. However the solutions l found online do not work. Because one
The Gridview does not only show data from one table but multiple so l cannot be specific in my query that l want delete the row of a certain table but just say l want to delete the row of the table showing. This goes for all the other events
Code for like editing GridView1.EditIndex = e.NewEditIndex does not work. It displays a
System.EventArgs error. NewEditIndex has no extension method and is
not accepting a first argument of type System.EventArgs could be
found.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings ["tlcString"].ConnectionString);
protected void DropDownList1_SelectedIndexChanged (object sender, EventArgs e)
{
con.Open ();
//Populates the gridview with the selectedindex in the list. The selectedindex being the table
SqlDataAdapter da = new SqlDataAdapter(string.Format ("Select * From {0}", drpTable.SelectedValue), con);
DataSet ds = new DataSet ();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
GridView1.DataSource = ds. Tables [0];
GridView1.DataBind ();
con.Close ();
}
private void BindData ()
{
//Binds the data in the gridview with the database table and updating it if changes are ever made. The method is called.
string strQuery = "Select * From {0}";
SqlCommand cmd = new SqlCommand (strQuery);
GridView1.DataSource = GetData (cmd);
GridView1.DataBind ();
}
private object GetData (SqlCommand cmd)
{
throw new NotImplentedException ();
}
//this is the code for the commads after l turned them into templatefields. But l only wrote code for the edit button only. It would be appreaciated if code for the other commands is supplied
protected void LinkButton1_Click (object sender, EventArgs e)
{
//Set edit index
GridView1.EditIndex = e.NewEditIndex;
BindData ();
}
//THATS all my code. The commands that were acting up were auto generated in the gridview properties window.
<asp:GridView ID="GridView1" runat="server" CellPadding="4"
ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server"
CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Select" Text="Select"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</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>

Related

I have a button in my item template and I want to program it so that it directs me to that specific job details

I have a page where I list all jobs. I have to program a button so that when I click on it, it directs me to that specific job details. How can I do that. I have tried navigateUrl but when I click on the button, nothing happens.
Here is my code for my item template
<asp:ListView ID="lsvJob" runat="server">
<ItemTemplate>
<div class="nf-item branding coffee spacing">
<div class="col-md-6 col-lg-4 mb-30">
<div class="service_box">
<figure>
<asp:Image ID="imgposter" ImageUrl='<%# Eval("HO_Image", "~/Images/{0}") %>'
runat="server" Height="300px" Width="300px" ImageAlign="Top" />
</figure>
<h3><%#Eval("Job_Name") %></h3>
<p>
<b>Employer Name:</b> <%# Eval("HO_LastName") %> <%# Eval("HO_FirstName") %>
<br />
<b>Email Address:</b> <%# Eval("HO_Email") %>
</p>
<asp:LinkButton ID="lnkmovdetails" runat="server" Text="View Details"
NavigateUrl='<%# Eval("Job_ID","~/jobdetails.aspx?id={0}")%>' CommandName="btnAccess" CssClass="btn btn-info"></asp:LinkButton>
</div>
</div>
</div>
</ItemTemplate>
</asp:ListView>
code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Configuration;
using System.Data.SqlClient;
namespace moCoolMaid
{
public partial class listjob : System.Web.UI.Page
{
private string _conString =
WebConfigurationManager.ConnectionStrings["MaidCS"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
// Create Connection
using (SqlConnection con = new SqlConnection(_conString))
{
// Create Command
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = " SELECT tblHO.*, tblJob.* FROM tblHO, tblJob WHERE tblJob.HO_ID=tblHO.HO_ID";
//Create DataReader
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
//Bind the reader to the repeater control
lsvJob.DataSource = reader;
lsvJob.DataBind();
con.Close();
}
}
}
}
Code in my jobdetail web form
<asp:DetailsView ID="dsvJob" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="10" GridLines="Vertical">
<AlternatingRowStyle BackColor="Gainsboro" />
<EditRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<Fields>
<asp:BoundField DataField="Job_Name" HeaderText="Job_Name" SortExpression="Job_Name" />
<asp:BoundField DataField="Job_Desc" HeaderText="Job_Desc" SortExpression="Job_Desc" />
<asp:BoundField DataField="Job_Salary" HeaderText="Job_Salary" SortExpression="Job_Salary" ItemStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Deadline_Date" HeaderText="Deadline_Date" SortExpression="Deadline_Date" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Min_Experience" HeaderText="Min_Experience" SortExpression="Min_Experience" />
<asp:BoundField DataField="Min_Qualification" HeaderText="Min_Qualification" SortExpression="Min_Qualification" />
</Fields>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MaidCS %>" SelectCommand="SELECT [Job_Name], [Job_Desc], [Job_Salary], [Deadline_Date], [Type], [Min_Experience], [Min_Qualification] FROM [tblJob]"></asp:SqlDataSource>
remove navigateUrl property from LinkButton and below one.
PostBackUrl="imagepage.aspx?v=<%#Eval("id") %>"
from query string you will get jobID. read JobId and display record.
Thanks, hope this will help you :)
Command Name does not work like this. Use below code for redirection
<asp:LinkButton ID="lnkmovdetails" runat="server" Text="View Details" PostBackUrl='~/jobdetails.aspx?id=<%#Eval("Job_ID") %>' CssClass="btn btn-info" />

(Gridview)1st record is being deleted from database c#

<asp:GridView ID="GridView1" runat="server" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Add Records">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" OnClick="btnadd_Click" CommandName="insert"
Text="Insert"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete Records">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="True" OnClick="btndelete_Click" CommandName="delete"
Text="delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="id">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%#Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Client Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%#Bind("client_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%#Bind("email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Google Email">
<ItemTemplate>
<asp:Label ID="lblgemail" runat="server" Text='<%#Bind("google_email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact Number">
<ItemTemplate>
<asp:Label ID="lblcont" runat="server" Text='<%#Bind("contact_number") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="role">
<ItemTemplate>
<asp:Label ID="lblrole" runat="server" Text='<%#Bind("role") %>'></asp:Label>
</ItemTemplate>
</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>
I have a table with 100 record
This is my Gridview I have two buttons add and delete(on Delete buttonClick particular record should be deleted from database) like, I clicked on record number 35(record number 35 should be deleted) but instead record number 1 is being deleted everytime.
public void delete()
{
foreach (GridViewRow g in GridView1.Rows)
{
Label lblname = (Label)g.FindControl("lblname");
Button btnde = (Button)g.FindControl("btndelete");
//Response.Redirect("cs.aspx");
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + lblname.Text + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
}
}
protected void btndelete_Click(object sender, EventArgs e)
{
delete();
GridView1.Visible = false;
}
This is my CS code.
It's because on delete you are deleting record using foreach loop which is not a good way to do. You could try out this:
public void delete(string Name)
{
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + Name + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
}
And on Delete button click find the particular row and send it to delete Method
protected void btndelete_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
string name = ((Label)gvr.FindControl("lblname")).Text;
delete(name);
GridView1.Visible = false;
}
Note: Also you could write your redirection inside button click event on basis of delete method return.
You can find your Label control position and get their value, then delete from database. It will work fine.
public void delete()
{
foreach (GridViewRow g in GridView1.Rows)
{
if(g.RowType == DataControlRowType.DataRow)
{
Label lblname = (Label)g.FindControl("lblname");
SqlCommand cmd = new SqlCommand("delete from clientrequest where client_name='" + lblname.Text + "'", con);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("welcome.aspx");
con.Close();
break;
}
}
}

How to fetch data from a column of a gridview and perform arithmetic operations on the column?

I am working on a Cart project, and using Visual Studio 2010 with SQL server express. I am using a Gridview to display data from my cart table in my database. I have a product table in my database , and I insert products from product table to the cart table . after that i display the cart in the gridview. the problem I am facing is i cannot use the Price column from my gridview to add the prices of the items in the cart to display the total price of the order. how can i do that?
my asp gridview source code is as follows
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" CssClass="table table-condensed" DataSourceID="SqlDataSource1"
ForeColor="#333333" GridLines="None"
onselectedindexchanged="GridView1_SelectedIndexChanged"
DataKeyNames="serial_no" onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="serial_no" InsertVisible="False"
SortExpression="serial_no">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("serial_no") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("serial_no") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" ControlStyle-CssClass="cart_menu" >
</asp:BoundField>
<asp:BoundField DataField="Quantity" HeaderText="Quantity"
SortExpression="Quantity" />
<asp:BoundField DataField="Price" HeaderText="Price"
SortExpression="Price" />
<asp:TemplateField HeaderText="Delete" SortExpression="serial_no">
<EditItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("serial_no") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandName="Delete"
onclick="Button1_Click1" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#FF7800" Font-Bold="True" ForeColor="White" CssClass="cart_menu" />
<HeaderStyle BackColor="#FF7800" Font-Bold="True" ForeColor="White" CssClass="cart_menu" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFFFF" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
my sqldatasource
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:cs %>"
ProviderName="<%$ ConnectionStrings:cs.ProviderName %>"
SelectCommand="SELECT cartdemo.serial_no, Product.Name, Product.P_Image, Product.Price, cartdemo.Quantity FROM cartdemo INNER JOIN Product ON cartdemo.ProductID = Product.ProductID WHERE (cartdemo.CID = #cid)"
DeleteCommand="DELETE FROM cartdemo WHERE (serial_no = #sl_no)">
<DeleteParameters>
<asp:Parameter Name="sl_no" />
</DeleteParameters>
<SelectParameters>
<asp:SessionParameter Name="cid" SessionField="ssid" />
</SelectParameters>
</asp:SqlDataSource>
my c# code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class cart2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow grd = e.Row;
switch (grd.RowType)
{
case DataControlRowType.DataRow:
{
Button btn = (Button)grd.FindControl("Button1");
if (btn != null)
{
Label lbl_pid = (Label)grd.FindControl("Label1");
btn.CommandArgument = lbl_pid.Text;
}
break;
}
}
calTotal(4);
}
protected void Button1_Click1(object sender, EventArgs e)
{
Button btn = sender as Button;
string id = btn.CommandArgument;
SqlDataSource1.DeleteParameters[0].DefaultValue = id;
SqlDataSource1.Delete();
GridView1.DataBind();
}
public void calTotal(int curCol)
{
decimal valueColumn = 0;
//try
//{
foreach (GridViewRow row in GridView1.Rows)
{
valueColumn = valueColumn + Convert.ToDecimal(row.Cells[curCol].Text);
}
//}
//catch(Exception r)
//{
//}
Label3.Text = "Rs." + valueColumn.ToString();
}
}
If I am understanding your question correctly, what you are wanting to know about is the SQL function "SUM". You can find more information about sum here. The short version is that SUM returns the total for a column of NUMERIC data. The basic syntax looks something like this:
SELECT SUM(myColumn)
FROM myTable;
/* Assume myColumn contains {0, 1, 2, 3, 4, 5} */
/* The output of this SELECT statement would be {15} */

Unable to get data from TextBox/DDL in Gridview

I have been looking all over web and testing what I think would work. I feel close but I guess not close enough. I need help pull the data in. The button click is to submit/insert data into the DB which I have not completed that part. Right now I am working on just getting data from the Gridview and need help.
The Update Button is outside the Gridview. I want end user to complete GridView then click update to submit data from Gridview to database.
Here is ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="dsSnumbers" OnRowDataBound="GridView1_RowDataBound"
GridLines="Horizontal" BackColor="White" BorderColor="#336666" BorderStyle="Double"
BorderWidth="3px">
<Columns>
<asp:TemplateField HeaderText="SerialNumber">
<ItemTemplate>
<asp:TextBox ID="TextBox1" BackColor="BurlyWood" runat="server" Text='<%# Eval("SerialNumber") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DdStatus" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:DropDownList ID="DdDept" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" RepeatLayout="Flow" RepeatDirection="Horizontal"
runat="server">
<asp:ListItem Text="Modify?" Value="1">
</asp:ListItem>
</asp:CheckBoxList>
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
<%-- <EmptyDataTemplate></EmptyDataTemplate>--%>
</asp:GridView>
And here is the .CS side
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
int RI = g1.RowIndex;
//SqlConnection con = new SqlConnection(connStr);
TextBox test = (TextBox)g1.Cells[0].FindControl("TextBox1");
TextBox test1 = (TextBox)g1.Cells[1].FindControl("TextBox1");
GridViewRow Grow = (GridViewRow)g1.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("TextBox1");
DropDownList testdd1 = (DropDownList)g1.Cells[0].FindControl("DdStatus");
DropDownList testdd2 = (DropDownList)g1.Cells[1].FindControl("DdStatus");
string test1324 = g1.Cells[1].Text;
string test2 = g1.Cells[2].Text;
string test3 = g1.Cells[3].Text;
}
}
Update:
When I run the below I can read the button click whether it is checked or not. However the textbox and dropdown still do nothing. I show ONLY rindex is pulling values. None of the others.
foreach (GridViewRow row in GridView1.Rows)
{
int rindex = row.DataItemIndex;
//string Test = ((TextBox)(row.Cells[0].Controls[0])).Text;
TextBox IDNum = (TextBox)row.FindControl("TextBox1");
string textBox1 = ((TextBox)row.FindControl("TextBox1")).Text;
string ddl1 = ((DropDownList)row.FindControl("DdStatus")).SelectedValue;
string ddl2 = ((DropDownList)row.FindControl("DdDept")).SelectedValue;
int ddl1231 = ((DropDownList)row.FindControl("DdStatus")).SelectedIndex;
int ddl1232 = ((DropDownList)row.FindControl("DdDept")).SelectedIndex;

Insert image into database from asp.net gridview

Below is my UI and Table. I wanted to insert image of a child inside the gridview, which will be saved in the database as well. Please assist how i suppose to achieve this.
Datatype for image on table is varchar(MAX).
here is what i have done so far.
(C# Code)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace MyProject
{
public partial class managechild : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["lolConnectionString1"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
string session = System.Web.HttpContext.Current.User.Identity.Name;
Response.Cookies["uname"].Value = session;
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "SELECT * from child c join parent p on c.ParentId = p.ParentId join login l on l.Username = p.UserId where l.Username ='" + session + "'";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
gvUpload.DataSource = ds;
gvUpload.DataBind();
conn.Close();
}
protected void btnUpload_OnClick(object sender, EventArgs e)
{
TextBox txtName = (TextBox)gvUpload.SelectedRow.FindControl("ChildName");
FileUpload fuploadFile = (FileUpload)gvUpload.SelectedRow.FindControl("fUpload");
Button btnUpload = (Button)gvUpload.SelectedRow.FindControl("btnUpload");
if (fuploadFile.HasFile)
{
string fileName = fuploadFile.FileName;
string exten = Path.GetExtension(fileName);
//here we have to restrict file type
exten = exten.ToLower();
string[] acceptedFileTypes = new string[4];
acceptedFileTypes[0] = ".jpg";
acceptedFileTypes[1] = ".jpeg";
acceptedFileTypes[2] = ".gif";
acceptedFileTypes[3] = ".png";
bool acceptFile = false;
for (int i = 0; i <= 3; i++)
{
if (exten == acceptedFileTypes[i])
{
acceptFile = true;
}
}
if (!acceptFile)
{
lblMsg.Text = "The file you are trying to upload is not a permitted file type!";
}
else
{
//upload the file onto the server
fuploadFile.SaveAs(Server.MapPath("~/images/child/"+fileName));
conn.Open();
string cmdstr = "insert into Child (Image) values (#photo)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#photo", "images/child/"+fileName);
cmd.ExecuteNonQuery();
conn.Close();
BindGrid();
}
}
}
}
}
UI Code (asp.net)
<asp:GridView ID="gvUpload" runat="server" AutoGenerateColumns="False"
ShowFooter="True" CellPadding="4" ForeColor="#333333" GridLines="None"
style="margin-left: 128px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Child Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#DataBinder.
Eval(Container.DataItem, "ChildName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="imgPhoto" runat="server" Width="100px" Height="120px"
ImageUrl='<%#DataBinder.Eval(Container.DataItem, "Image") %>' />
</ItemTemplate>
<ItemTemplate>
<asp:FileUpload ID="fUpload" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="btnUpload_OnClick" />
</ItemTemplate>
</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>
When posting on SO pls make sure to show at least some attempt to solve the problem yourself before asking others for complete solution.
One way is to save image in database as binary data in which case you'll need to add varbinary column to your table.
Another way is to only save the path to the image and save the image in some folder on the server.
If you don't have a lot of images I'd suggest you go with the second solution as it will be easier to implement. Just look up how to upload image file and you'll be on the right track.

Categories

Resources