Grid view index changing with filters - c#

I got this simple gridview
<asp:GridView ID="GridViewFoundations" runat="server" AutoGenerateColumns="False"
Width="100%" AllowPaging="True" AllowSorting="True" PageSize="15"
CellPadding="4" ForeColor="#333333" GridLines="None"
onpageindexchanging="GridViewFoundations_PageIndexChanging">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate><asp:Label ID="lb_id" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "nodeId") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Foundation Name">
<ItemTemplate><asp:Label ID="lb_foundationName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "text") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastUpdate">
<ItemTemplate><asp:Label ID="lb_lastUpdate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "updateDate") %>'></asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expire Date">
<ItemTemplate><asp:Label ID="lb_expireDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "expireDate") %>'></asp:Label></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>
Then I bind if on the page load event , like this
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
protected void BindData()
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
And i have the following filter (for example by text)
protected void btn_filtro_Click(object sender, EventArgs e)
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId and text like '%" + TextBox1.Text + "%' group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
My problem is I can't change the index of the page and keep my filters on..
I have already tried
GridViewFoundations.PageIndex = e.NewPageIndex
followed by
gridviewFoundations.Databind() or BindData()
but in the 1st case the gridview desapears and in the second it clears all the filters (obviously) .
So Can anyone help me changing the page of the grid with filters?

In first case(GridViewFoundations.PageIndex = e.NewPageIndex followed by gridviewFoundations.Databind() ) data disappears as you are not providing any datasource to rebing your grid after postback.
In second case(BindData()) you are binding grid without any filters, hence your filter is lost.
what you can do is create a new function
protected void BindFilteredData()
{
string sqlConnectString = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ToString();
string sqlSelect = "SELECT cmsContentXml.nodeId,text, Max(updateDate) as UpdateDate,expireDate as ExpireDate from cmsContentXml,cmsDocument,cmsContent where cmsContent.nodeId=cmsContentXml.nodeId and cmsDocument.nodeId=cmsContent.nodeId and text like '%" + TextBox1.Text + "%' group by cmsContentXml.nodeId,text,expireDate";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
DataTable sqlDt = new DataTable();
sqlDa.Fill(sqlDt);
GridViewFoundations.DataSource = sqlDt;
GridViewFoundations.DataBind();
}
And on page load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
else
BindFilteredData();
}
This will call BindData when your page loads first time and rest of the times it will call filtered data function.

Related

database is showing all 0's when the checked boxes should show one

I am rather new to programming in general. I am creating an webpage where the user selects a process from a sql populated dropdown list. A grid view then populates with the corresponding results with checkboxes. The end user can select a checkbox and that should save the value 1 to the database so that I can retrieve the checked items for another grid view later. Unfortunately it is only populating zeros. How can i fix this?
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
if (checkBox1.Checked)
{
string updateData = "update AuditChecklist$ set IsSelected = #IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", 1);
cmd.ExecuteNonQuery();
con.Close();
}
else if(!checkBox1.Checked)
{
string updateData = "update AuditChecklist$ set IsSelected = #IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", 0);
cmd.ExecuteNonQuery();
con.Close();
}
}
Tried the following code as suggested but I am still having the same issue. I have included my design and ASP code for further help.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
string updateData = "update AuditChecklist$ set IsSelected = #IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", checkBox1.Checked ? 1 : 0);
cmd.ExecuteNonQuery();
con.Close();
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource2" ForeColor="#333333" GridLines="None" Height="377px" Width="764px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Select">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="FAST_Screen" HeaderText="FAST Screen" SortExpression="FAST_Screen">
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="Audit_Detail" HeaderText="Audit Detail" SortExpression="Audit_Detail">
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Delete</asp:LinkButton>
</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>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:QMSAuditConnectionString %>" SelectCommand="SELECT [FAST Screen] AS FAST_Screen, [Audit Detail] AS Audit_Detail, [EPS Process] AS EPS_Process, [IsSelected] FROM [AuditChecklist$] WHERE ([EPS Process] = #EPS_Process)">
<SelectParameters>
<asp:ControlParameter ControlID="LstProcess" Name="EPS_Process" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Design
It seems you set the ThreeState property of CheckBox to true, so it must be changed to false.
It doesn't need write same codes twice only for one check condition.
CheckBox checkBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
string updateData = "update AuditChecklist$ set IsSelected = :#IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", checkBox1.Checked ? 1 : 0);
cmd.ExecuteNonQuery();
con.Close();
Also it will be better if an update statement has any filter (using where clause).

asp.net gridview sum and quantity of the columns

i have a small problem with summarizing of the total value of the columns. I have a shopping cart where i want to summarize quantity and price of the item. I've done summarize of prices but when i was trying to multiply it to quantity it didn't work.
.
Could you please give me an advice.
Here is a gridview:
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" DataKeyNames="id" ShowFooter="true" ShowHeaderWhenEmpty="true">
<Columns>
<asp:BoundField DataField="item" HeaderText="Item" SortExpression="item"></asp:BoundField>
<asp:BoundField DataField="BEE" HeaderText="Description" SortExpression="BEE"></asp:BoundField>
<asp:BoundField DataField="count" HeaderText="Quantity" SortExpression="count"></asp:BoundField>
<asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price"></asp:BoundField>
<asp:TemplateField>
<FooterTemplate>
<asp:Label ID="lbltxtTotal" runat="server" Text="Total Price" />
</FooterTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" SortExpression="id"></asp:BoundField>
<asp:ButtonField CommandName="Delete" Text="Delete" ButtonType="Button" ShowHeader="True" HeaderText="Delete"></asp:ButtonField>
</Columns>
<EmptyDataTemplate>No Record Available</EmptyDataTemplate>
<FooterStyle BackColor="White" Font-Bold="True"></FooterStyle>
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Right" BackColor="White" ForeColor="Black"></PagerStyle>
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#F7F7F7"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#4B4B4B"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#E5E5E5"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#242121"></SortedDescendingHeaderStyle>
</asp:GridView>
and here is a backend:
protected void Timer1_Tick(object sender, EventArgs e)
{
string Username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
string Username_new = Username.Replace("APAC\\", "");
GridView1.DataBind();
//live data
String myquery = "Select * from Basket where Username='" + Username_new + "'";
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
GridView1.FooterRow.Cells[1].Text = "Total Amount";
GridView1.FooterRow.Cells[2].Text = dt.Compute("Sum(price)", "").ToString();
}
This is easy.
Add method to your code:
protected void getSUM()
{
// SQL query that gets total of product sales where category id = 1
string SqlQuery = #"SELECT SUM(ProductSales) AS TotalSales
FROM [NORTHWIND].[dbo].[Sales by Category]
WHERE CategoryID = 1";
// Declare and open a connection to database
SqlConnection conn = new SqlConnection(
ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString);
conn.Open();
// Creates SqlCommand object
SqlCommand comm = new SqlCommand(SqlQuery, conn);
// Gets total sales
decimal TotalSales = Convert.ToDecimal(comm.ExecuteScalar());
// Close connection
conn.Close();
conn.Dispose();
comm.Dispose();
// Adds formatted output to GridView footer
GridView1.Columns[1].FooterText = String.Format("{0:c}", TotalSales);
}
In markup code, we'll define footer template and call getSUM method:
<FooterTemplate>
Total sales: <%# getSUM(); %>
</FooterTemplate>

Reading values in Gridview on Selection change of a DropDownList

I am really bad when it comes to playing with data inside a gridview. Here i have a simple gridview that contains a dropdownlist that gets its data from the database table Products.
what i want is on dropdownlist OnSelectedIndexChanged, the price label should read the price of the selected product in dropdownlist. the issue is when i select a product in dropdownlist the prices doesn't show. label remains empty.
ASP.NET
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" AllowPaging="true" PageSize="5" OnRowDataBound="Gridview1_RowDataBound">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="#">
<HeaderStyle CssClass="header" Width="60px"></HeaderStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:DropDownList ID="dropdown1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropdown1_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle CssClass="header" />
<ItemStyle Width="170px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="QTY">
<ItemTemplate>
<asp:TextBox ID="qty_txtbox" runat="server" style="text-align:center;" OnTextChanged="TextBox2_TextChanged"></asp:TextBox>
</ItemTemplate>
<ControlStyle Width="50px" CssClass="txt" />
<HeaderStyle CssClass="header" />
<ItemStyle Width="50px" CssClass="txt" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Price (AED)">
<ItemTemplate>
<asp:Label ID="amount_lbl" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle CssClass="header" />
<ItemStyle Width="130px" CssClass="txt" />
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton runat="server" ID="trash" Style="height: 20px;" ImageUrl="~/IMG/garbage.png" />
</ItemTemplate>
<ControlStyle Height="20px" Width="20px"></ControlStyle>
<FooterStyle HorizontalAlign="center" />
<HeaderStyle Height="30px" Width="30px" CssClass="header"></HeaderStyle>
<FooterTemplate>
<asp:ImageButton runat="server" ID="addnew" ImageUrl="~/IMG/add.png" Style="height: 20px;" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="header" />
<PagerStyle CssClass="pagerr" />
<RowStyle CssClass="rows" />
</asp:GridView>
Here is what i tried
private DataSet GetData()
{
SqlCommand cmd = new SqlCommand("SELECT ProductName, PartNumber, price FROM Products");
using (SqlConnection con = new SqlConnection(cDate.CS))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddproducts = (e.Row.FindControl("dropdown1") as DropDownList);
ddproducts.DataSource = GetData();
ddproducts.DataTextField = "ProductName";
ddproducts.DataValueField = "ProductName";
ddproducts.DataBind();
//Add Default Item in the DropDownList
ddproducts.Items.Insert(0, new ListItem("<----Please select---->"));
}
}
protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
string dvalue = Gridview1.SelectedRow.Cells[1].Text;
string price = Gridview1.SelectedRow.Cells[3].Text;
using (SqlConnection con = new SqlConnection(cDate.CS))
{
con.Open();
SqlCommand myCommand = new SqlCommand("select price from products where ProductName = #name");
myCommand.Parameters.AddWithValue("#name", dvalue);
myCommand.Connection = con;
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
while (myReader.Read())
{
price = (myReader["price"].ToString());
}
}
}
}
Error
Object reference not set to an instance of an object. for this line string dvalue = Gridview1.SelectedRow.Cells[1].Text;
As the other answer stated, the issue main issues is you are not updating the result in that particular label. But that only solves your issues, you have do something more:
Identify the DataRow in which the control belongs to..
Get the label that you wanted to access.
Perform the operations
Assign the value back to the label.
The whole process can be implemented by using the following code, please take a look and let me know if you need any clarifications:
protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlProduct = (DropDownList)sender;
DataGridItem row = (DataGridItem) ddlProduct.NamingContainer;
Label lblPrice = (Label)row.FindControl("amount_lbl");
// Get current label Text
string price = lblPrice.Text;
// Perform your operations here
// Assign the price value back to the label
lblPrice.Text = price;
}
It seems that you didn't set the price back to the grid!
Update: as mentioned by 'un-lucky', to get appropriate grid row we have use the dropdown which fires the event and get associated DataRow in its parents:
protected void dropdown1_SelectedIndexChanged(object sender, EventArgs e)
{
var row = (sender as DropDownList).NamingContainer as GridViewRow; //instead of Gridview1.SelectedRow;
string dvalue = row.Cells[1].Text; //or row.FindControl(id);
//string price = row.Cells[3].Text;
string price = "1400"; //get from database
row.Cells[3].Text = price; //or row.FindControl(id);
//Gridview1.new
}

Issue with updating rows in a gridview

I have gridview where users can edit and update data in gridview but my issue is when i put some text in the Action field, nothing is updated. I have tried to run debug mode so i can watch what what is happening but i don't see the values i typed in the text box, it shows blank in my variable. Here is my aspx code:
<asp:GridView ID="GridView1" runat="server" Width = "855px" AutoGenerateColumns = "False" Font-Names = "Arial"
OnPageIndexChanging = "OnPaging" onrowediting="EditGridView1"
onrowupdating="UpdateGridView1" onrowcancelingedit="CancelEdit" CellPadding="3"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "ID">
<ItemTemplate>
<asp:Label ID="lblQST_SK" runat="server" Text='<%# Eval("QUEST_SK")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="10px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Action">
<ItemTemplate>
<asp:Label ID="lblAction" runat="server" Text='<%# Eval("ACTION")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAction" runat="server" Text='<%# Eval("ACTION")%>' TextMode="MultiLine" Height="80px"></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White"
HorizontalAlign="Left" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
</asp:GridView>
here is my code behind:
protected void UpdateGridView1(object sender, GridViewUpdateEventArgs e)
{
string QUEST_SK = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblQST_SK")).Text;
string ACTION = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAction")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update mytable set ACTION=#ACTION" +
"where QUEST_SK=#QUEST_SK;" +
"SELECT QUEST_SK, ACTION FROM mytable";
cmd.Parameters.Add("#QUEST_SK", SqlDbType.VarChar).Value = QUEST_SK;
cmd.Parameters.Add("#ACTION", SqlDbType.VarChar).Value = ACTION;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Try to write the function below in Page Load Event :
Page_Load()
{
if(IsPostBack)
{
return`;
}
}

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