Fill Data Table with image data as byte array in C# - c#

So I have the data table filled but the column I need image data in is not working. I can see the table filled and can see it is reading the data, but not as a byte array, nor is it displaying the image.
public void Bindformview()
{
try
{
SqlDataAdapter adp = new SqlDataAdapter("Select * from Recipes", con);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
And I know I need to insert this code, or something like it that pulls the data out of the db "thumbnail varbinary(MAX)" column as a byte stream, to get the byte array for the image to display properly:
DataColumn column = new DataColumn("MyImage"); //Create the column.
column.DataType = System.Type.GetType("System.Byte[]"); //Type byte[] to store image bytes.
column.AllowDBNull = true;
column.Caption = "My Image";
table.Columns.Add(column); //Add the column to the table.
and this:
DataRow row = table.NewRow();
row["MyImage"] = <Image byte array>;
tables.Rows.Add(row);
But I do not need a new column or a new row as those fields are already there.
So how to I fill column "Thumbnail" in the data table, with byte array data to display and where do I do the insert of said code, before the if statement that loads the dt, in the if statement that binds the dt?
do I do it by stating the column like so:
dt.column.thumbnail.fill(byte[] bytes = (byte[])cmd.ExecuteScalar());
and then put this in to fill the formview image1 ID like so?
string strBase64 = Convert.ToBase64String(bytes);
formviewrecipes.Image1.ImageUrl = "data:Image/png;base64," + strBase64;
I am just at a standstill and not sure how to do this.
So to be clear, I already have the DB with the Proper image info, and can display it by <asp:image id=image1...etc />, with other code that retrieves the image outside of the formview using this code,
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetImageByID", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#Id",
Value = Request.QueryString["Id"]
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
}
but it doesn't work in a <asp:FormView...etc/> and I need to be able to have it do so for page formating.
This is why I was going in this direction, of using a Data Table right now. If you have a better solution I am open to trying it, as long as it can be used inside of the <asp:formview /> element. Thank you.

So I figured it out:
I Needed to add an Object o; and this line after the databind o = dt.Rows[0]["RecipeId"];
Like So:
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
//lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
o = dt.Rows[0]["RecipeId"];
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
and made the call to load the image as so:
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#RecipeId",
Value = o //Object from the datatable
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
if (bytes != null)
{
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
else
{
Image1.ImageUrl = "~/images/NoImageAvail.jpg";
}
}
Here is the code below if anyone else needs to do the same thing. I will be putting together a for/while or for/next for going through multiple data base entries to display at the same time instead of one at a time currently in this <asp:forview...></formview> element setup.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.IO;
using System.Data.SqlClient;
namespace DB_Test1
{
public partial class Search_Results_1 : System.Web.UI.Page
{
string b;
Object o;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Search"] != null)
{
if (Request.QueryString["Text"] != null)
{
string a = Request.QueryString["Text"];
b = a;
recipeSearch(a);
}
}
}
protected void recipeSearch(string a)
{
//Search the database
con.Open();
try
{
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM Recipes WHERE Type LIKE '%" + a + "%'", con);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
FormViewRecipes.DataSource = dt;
FormViewRecipes.DataBind();
//lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
o = dt.Rows[0]["RecipeId"];
}
else
{
FormViewRecipes.DataSource = null;
FormViewRecipes.DataBind();
}
}
catch (Exception ex)
{
//throw new ApplicationException("operation failed!", ex);
}
con.Close();
FormViewRecipes.Visible = true;
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter()
{
ParameterName = "#RecipeId",
Value = o //Object from the datatable
};
cmd.Parameters.Add(paramId);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
if (bytes != null)
{
string strBase64 = Convert.ToBase64String(bytes);
Image1.ImageUrl = "data:Image/png;base64," + strBase64;
}
else
{
Image1.ImageUrl = "~/images/NoImageAvail.jpg";
}
}
Image1.Visible = true;
}
protected void FormViewRecipes_PageIndexChanging(object sender, FormViewPageEventArgs e)
{
string a = b;
FormViewRecipes.PageIndex = e.NewPageIndex;
recipeSearch(a);
}
}
}
And here is the ASPX page code:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<hr />
<div class="row">
<div class="col-md-8">
<table>
<tr>
<td>
<asp:Image ID="Image1" runat="server" visable="false" Height="150px" Width="150px"/>
</td>
<td>
<asp:FormView ID="FormViewRecipes" runat="server" DataKeyNames="RecipeId" AllowPaging="True"
onpageindexchanging="FormViewRecipes_PageIndexChanging" Visible="false">
<%--<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />--%>
<ItemTemplate>
<table style="border:1px solid #c1c1c1;">
<tr style="background-color:white;font-weight:bold"><td><%--Recipe Detail--%></td><td>
<%--<asp:Image id="Image1" runat="server" ImageUrl='<%# Eval("Thumbnail") %>'
AlternateText='<%# Eval("ThumbnailAltTxt") %>'
Height="100px" Width="100px" />--%></td>
</tr>
<tr><td><b>Title:- </b></td><td>
<asp:Label ID="lblRecipeTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label></td></tr>
<tr><td><b>Ingredients:- </b></td><td>
<asp:Label ID="lblIngredients" runat="server" Text='<%# Eval("Ingredients") %>'></asp:Label></td></tr>
<tr><td><b>Directions:- </b></td><td>
<asp:Label ID="lblDirections" runat="server" Text='<%# Eval("Directions") %>'></asp:Label></td></tr>
<tr><td><b>Notes:- </b></td><td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Notes") %>'></asp:Label></td></tr>
</table>
</ItemTemplate>
<EmptyDataTemplate>
<table style="border:1px solid #c1c1c1;">
<tr style="background-color:#E5E5FE;font-weight:bold"><td><b>Recipe</b></td></tr>
<tr><td><b>Recipe Title:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
<tr><td><b>Recipe Ingredients:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
<tr><td><b>Recipe Directions:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
</table>
</EmptyDataTemplate>
</asp:FormView>
</td>
</tr>
</table>
</div>
<div class="col-md-4">
<p>Ad Space</p>
<asp:Label ID="lblDataTable" runat="server"></asp:Label>
</div>
</div>
</asp:Content>
Just remember I commented out the <asp:image..../a> element field that is in the <Asp:formview.../> element and reset my page layout to get how I wanted it to look for testing.

Related

Use Checkbox to Insert or Delete a row in Database

I am trying to update a single record in a DataList. I have chosen the DataList type so that I can have a horizontal row with many records on the same page, can use the page to take attendance from a pre-determined list of people, but I want to update as I go. I will be using volunteers to take attendance and don't want to force the users to click save after they are finished (They may get distracted and forget to do so). So, each check box marks a person present. Or unchecking marks them absent.
Here is my CSHTML page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AttendanceTaking.aspx.cs" Inherits="AtChurch.AttendanceTaking" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<style>.ChkBoxClass input {width:25px; height:25px;}
.auto-style1 {
width: 32px;
}
.auto-style2 {
width: 183px;
}
</style>
<table>
<tr>
<td class="auto-style2"><strong>Take Attendance</strong></td>
<td class="auto-style1">Date:</td>
<td>
<strong>
<asp:Label ID="lblAttendanceDate" runat="server"></asp:Label>
</strong>
</td>
<td>
Attendance Group:</td>
<td>
<strong>
<asp:Label ID="lblAttendanceGroup" runat="server" ></asp:Label>
</strong>
</td>
</tr>
</table>
<p>
<asp:HiddenField ID="HiddenAttendanceDate" runat="server" />
<asp:HiddenField ID="HiddenSoCID" runat="server" />
</p>
<p>
<asp:DataList RepeatDirection="Horizontal" RepeatColumns="6" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Both">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<ItemStyle ForeColor="#000066" />
<ItemTemplate>
<asp:CheckBox ID="CheckBoxPresent" runat="server" RowNumber='<%# Eval("RowNumber") %>' AttendanceID='<%# Eval("AttendanceID") %>' PeopleId='<%# Eval("PeopleID") %>' Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true" />
<asp:Label ID="RowNumber" runat="server" Text='<%# Eval("RowNumber") %>' />
<asp:Label ID="FullName" runat="server" Text='<%# Eval("FullName") %>' />
<asp:Label ID="PeopleID" runat="server" Text='<%# Eval("PeopleID") %>' />
<asp:Label ID="AttendanceID" runat="server" Text='<%# Eval("AttendanceID") %>' ></asp:Label>
<asp:Label ID="AttendLabel" runat="server" Text="&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"></asp:Label> <br />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<FooterTemplate>
:
</FooterTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AtChurchConString %>" SelectCommand="sp_AttendanceTaking" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="ChurchID" DefaultValue="0" Name="ChurchID" PropertyName="Value" />
<asp:ControlParameter ControlID="HiddenSoCID" DefaultValue="0" Name="HiddenSoCID" PropertyName="Value" />
<asp:Parameter DefaultValue="1" Name="Select" Type="Int32" />
<asp:ControlParameter ControlID="HiddenAttendanceDate" DefaultValue="" Name="AttendanceDate" PropertyName="Value" Type="DateTime" />
<%--<asp:ControlParameter ControlID="CheckBoxPresent" DefaultValue="0" Name="CheckBoxPresent" PropertyName="Value" />--%>
<%-- <asp:ControlParameter ControlID="AttendanceID" DefaultValue="0" Name="AttendanceID" PropertyName="Value" />--%>
<%--<asp:ControlParameter ControlID="PeopleID" DefaultValue="0" Name="PeopleID" PropertyName="Value" />--%>
</SelectParameters>
</asp:SqlDataSource>
<asp:HiddenField ID="ChurchID" runat="server" />
</p>
<p>
</p>
</asp:Content>
And here is my CS page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Web.SessionState;
namespace AtChurch
{
public partial class AttendanceTaking : System.Web.UI.Page
{
private static string strcon = WebConfigurationManager.ConnectionStrings["AtChurchConString"].ConnectionString;
// Need these for Security
public string strRole, strChurchID, strAttGroup, strAttDate;
public bool ValidUser { get; private set; }
// Checkbox Checked?
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
//start of checkbox
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
//DataList1.DataBind();
foreach (DataListItem itm in DataList1.Items)
{
if (itm.ItemType == ListItemType.Item )
{
string strPeopleID = ((Label)itm.FindControl("PeopleID")).Text;
string strAttendanceID = ((Label)itm.FindControl("AttendanceID")).Text;
Response.Write(strPeopleID);
Response.End();
//string strAttID = "";
//strAttID = ((DataBoundLiteralControl)item.Controls[1]).Text;
if (ChkBxPresentState == true)
{
Response.Write("Let's Insert it...");
Response.Write(strPeopleID);
Response.End();
}
else
{
//Response.Write("Let's Remove it...");
//Response.End();
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
//cmdDelete.Parameters.Add(new SqlParameter("#HiddenSoCID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
cmdDelete.Parameters.Add(new SqlParameter("#CheckBoxPresent", SqlDbType.Int));
//cmdDelete.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttendanceID.ToString(), out int intAttendanceID)) { }
Response.Write(intAttendanceID);
Response.Write("-");
Response.Write(1);
Response.End();
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#CheckBoxPresent"].Value = 0;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
// End delete data
}
}
}
//end of checkbox
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
if (!IsPostBack)
{
// Get Attendance Group ID from the Attendance page.
//if (Request.QueryString["SoCID"].ToString() != null && Request.QueryString["SoCID"].ToString() != null)
string SoCID = Server.UrlDecode(Request.QueryString["SoCID"]);
string AttendanceDate = Server.UrlDecode(Request.QueryString["AttendanceDate"]);
// Response.Write("ok?"+AttendanceDate);
// Response.End();
if (SoCID != null && AttendanceDate != null)
{
strAttGroup = SoCID;
HiddenSoCID.Value = strAttGroup;
lblAttendanceGroup.Text = strAttGroup;
strAttDate = AttendanceDate;
HiddenAttendanceDate.Value = strAttDate;
lblAttendanceDate.Text = strAttDate;
//strAttDate = Request.QueryString["AttendanceDate"].ToString();
//Response.Write(strAttGroup);
//Response.Write(strAttDate);
//Response.End();
}
else
{
//Response.Write("error");
Response.Redirect("Attendance.aspx");
Response.End();
}
}
// Security Start
if (Session["Role"] is null && Session["ChurchID"] is null)
{
Response.Redirect("Login.aspx");
return;
}
if (Session["Role"] != null && Session["ChurchID"] != null)
{
if (!string.IsNullOrEmpty(Session["Role"].ToString()))
{
strRole = Session["Role"].ToString();
strChurchID = Session["ChurchID"].ToString();
}
}
if (strRole == ("SuperAdmin") || strRole == ("ChurchAdmin"))
{
ValidUser = true;
}
if (ValidUser != true)
{
Response.Redirect("Login.aspx");
}
// Security End
//Populate the ChurchID for Insert
ChurchID.Value = strChurchID;
}
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button_AttendanceTaker_Command(object sender, CommandEventArgs e)
{
}
}
}
This is just the button code of which I am working with to add or delete using my stored procedure.
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
//start of checkbox
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
// I added this to try to compare to to get a specific row for Insert
string BoxIndex = ChkBxPresent.Attributes["RowNumber"];
//DataList1.DataBind();
foreach (DataListItem itm in DataList1.Items)
{
// I added this to try to compare to within the Item List
string ItmIndex = ((Label)itm.FindControl("RowNumber")).Text;
if (itm.ItemType == ListItemType.Item)
{
// Let's gather the parameter data needed
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
string strAttendanceID = ChkBxPresent.Attributes["AttendanceID"];
string strCheckBoxPresent = ChkBxPresent.Attributes["IsChecked"];
string strAttGroupID = ((Label)itm.FindControl("SoCID")).Text;
string strAttendanceDate = ((Label)itm.FindControl("AttendanceDate")).Text;
// Here is what we do if the box is checked...
// I used this to try and compare the values. It showed the one I wanted to
// compare to but the ItmIndex only returned odd rows. So I don't match somtimes
//Response.Write("BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
// I added the compare of ItmIndex == BoxIndex but it was not consistent. Again it was only returning odd
// numbers and no even numbers to compare to for some reason.
if (ChkBxPresentState == true)
{
string strAction = "ADD";
//Response.Write("Add BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
SqlConnection con = new SqlConnection(strcon);
//Response.Write("Let's Insert it...");
//Response.Write("PeopleID");
//Response.Write(strPeopleID);
//Response.Write("ChurchID");
//Response.Write(strChurchID);
//Response.Write("GroupID");
//Response.Write(strAttGroupID);
//Response.Write("AttDate");
//Response.Write(strAttendanceDate);
//Response.Write("Action");
//Response.Write(strAction);
//Response.End();
SqlCommand cmdInsertData = new SqlCommand("sp_AttendanceTaking", con);
cmdInsertData.CommandType = CommandType.StoredProcedure;
cmdInsertData.Parameters.Add(new SqlParameter("#AttGroupID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdInsertData.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttGroupID.ToString(), out int intGroupID)) { }
if (Int32.TryParse(strPeopleID.ToString(), out int intPeopleID)) { }
if (Int32.TryParse(strChurchID.ToString(), out int intChurchID)) { }
//Response.Write(intAttendanceID);
//Response.Write("-");
//Response.Write(strAction);
//Response.End();
cmdInsertData.Parameters["#AttGroupID"].Value = intGroupID;
cmdInsertData.Parameters["#Action"].Value = strAction;
cmdInsertData.Parameters["#PeopleID"].Value = intPeopleID;
cmdInsertData.Parameters["#ChurchID"].Value = intChurchID;
cmdInsertData.Parameters["#AttendanceDate"].Value = strAttendanceDate;
con.Open();
cmdInsertData.ExecuteNonQuery();
con.Close();
}
else
{
string strAction = "DEL";
//Response.Write("DEL BoxIdx=");
//Response.Write(BoxIndex);
//Response.Write("and ItmIdx=");
//Response.Write(ItmIndex);
//Response.Write(" |");
// Here is what we do if the Box is unchecked
//Response.Write("Let's Remove it...");
//Response.Write(strPeopleID);
//Response.Write("aID");
//Response.Write(strAttendanceID);
//Response.Write("checkBoxPresent:");
//Response.Write(strCheckBoxPresent);
//Response.End();
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttendanceID.ToString(), out int intAttendanceID)) { }
//Response.Write(intAttendanceID);
//Response.Write("-");
//Response.Write(strAction);
//Response.End();
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#Action"].Value = strAction;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
// End delete data
}
}
}
//end of checkbox
}
It's obviously not complete as I'm just trying to get it to show the right data. I did a test of the delete portion (When the box is unchecked) and it did not delete a specific record because the EventArgs returns all the checkbox values. If I change it to DataListItemEventArgs it returns specific rows but then I lose the functionality of the checkbox on check. I think I need to separate these but I am not sure how to accomplish this task.
Here is the functionality I am going for:
1. Setup the date and retrieve any attendance if already taken.
Image of form that loads the AttendanceTaker
And a sample of the page I am going for with a large checkbox so it can be used on a tablet.
Sample of AttendanceTaker page
I rewrote the code using the idea from selected answer. This was the code that ended up working.
// Checkbox Checked?
protected void CheckBoxPresent_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBxPresent = sender as CheckBox;
Boolean ChkBxPresentState = ChkBxPresent.Checked;
if (Int32.TryParse(ChkBxPresent.Attributes["AttendanceID"].ToString(), out int intAttendanceID)) { }
// Let's gather the parameter data needed
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
string strAttendanceID = ChkBxPresent.Attributes["AttendanceID"];
string strCheckBoxPresent = ChkBxPresent.Attributes["IsChecked"];
string strAttGroupID = ChkBxPresent.Attributes["SoCID"];
string strAttendanceDate = ChkBxPresent.Attributes["AttendanceDate"];
if (intAttendanceID == 0) // Add Attendance Record it does not exist and was checked
{
string strAction = "ADD";
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmdInsertData = new SqlCommand("sp_AttendanceTaking", con);
cmdInsertData.CommandType = CommandType.StoredProcedure;
cmdInsertData.Parameters.Add(new SqlParameter("#AttGroupID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdInsertData.Parameters.Add(new SqlParameter("#PeopleID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#ChurchID", SqlDbType.Int));
cmdInsertData.Parameters.Add(new SqlParameter("#AttendanceDate", SqlDbType.DateTime));
// Convert Strings to Int where needed
if (Int32.TryParse(strAttGroupID.ToString(), out int intGroupID)) { }
if (Int32.TryParse(strPeopleID.ToString(), out int intPeopleID)) { }
if (Int32.TryParse(strChurchID.ToString(), out int intChurchID)) { }
cmdInsertData.Parameters["#AttGroupID"].Value = intGroupID;
cmdInsertData.Parameters["#Action"].Value = strAction;
cmdInsertData.Parameters["#PeopleID"].Value = intPeopleID;
cmdInsertData.Parameters["#ChurchID"].Value = intChurchID;
cmdInsertData.Parameters["#AttendanceDate"].Value = strAttendanceDate;
con.Open();
cmdInsertData.ExecuteNonQuery();
con.Close();
DataList1.DataBind();
}
else // Delete Attendance Record it was unchecked
{
string strAction = "DEL";
SqlConnection con = new SqlConnection(strcon);
// First let's delete this Groups Data
SqlCommand cmdDelete = new SqlCommand("sp_AttendanceTaking", con);
cmdDelete.CommandType = CommandType.StoredProcedure;
cmdDelete.Parameters.Add(new SqlParameter("#AttendanceID", SqlDbType.Int));
cmdDelete.Parameters.Add(new SqlParameter("#Action", SqlDbType.VarChar));
cmdDelete.Parameters["#AttendanceID"].Value = intAttendanceID;
cmdDelete.Parameters["#Action"].Value = strAction;
con.Open();
cmdDelete.ExecuteNonQuery();
con.Close();
DataList1.DataBind();
// End delete data
}
////end of checkbox
You can pass the value of the PeopleId (and/or attendanceID) in the checkbox as an attribute and avoid iterating over the DataList.
Your checkbox
<asp:CheckBox ID="CheckBoxPresent" runat="server" PeopleId='<%# Eval("PeopleID") %>' Text='<%# Eval("CheckBoxPresent") %>' Checked='<%# Eval("CheckBoxPresent").ToString().Equals("1") %>' CssClass="ChkBoxClass" OnCheckedChanged="CheckBoxPresent_CheckedChanged" AutoPostBack="true" />
Code behind
string strPeopleID = ChkBxPresent.Attributes["PeopleId"];
Then if it's checked, issue insert command for that ID only, if it's unchecked, issue delete command for that ID.

How can I render a empty grid view with Boolean table row in database?

Morning everyone, I'm a newbie of c#.
The code below
<asp:LinkButton ID="insert_new_user" runat="server" OnClick="insert_new_user_Click"
CommandName="insertnewuser" Text="add new user" BorderColor="#000099">
</asp:LinkButton>
<asp:TemplateField HeaderText="Resign?" SortExpression="BS_DEPT">
<ItemTemplate>
<asp:CheckBox ID="cb_isleave" runat="server" Checked='<%# Eval("BS_LEAVE") %>'
Visible="True" Enabled="False" ForeColor="#ff0000" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="ed_cb_isleave" runat="server" Checked='<%#Eval("BS_LEAVE") %>'
Visible="True" Enabled="true" ForeColor="#ff0000" />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="ft_cb_isleave" runat="server" Checked="false"
Visible="True" Enabled="true" />
</FooterTemplate>
</asp:TemplateField>
When the database is empty I use these code to render a empty footer row and header
protected void insert_new_user_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string fakequery_user = "SELECT TOP 1 [A].[BS_ID],[A].[BS_NAME_CHT],[BS_NAME_ENG] = ISNULL([A].[BS_NAME_ENG], '-'),[BS_LEAVE]=ISNULL([A].[BS_LEAVE],0),[B].[BS_NAME]" +
"FROM[BS_USER][A] LEFT OUTER JOIN[BS_DEPT][B] ON[A].[BS_DEPT] = [B].[BS_ID]";
SqlCommand fakequery = new SqlCommand(fakequery_user, conn);
conn.Open();
SqlDataAdapter da1 = new SqlDataAdapter(fakequery);
SqlDataReader dr = fakequery.ExecuteReader();
if (dr.HasRows)
{
DataTable FinalUserData = this.Bulid_UserTB();
conn.Close();
conn.Open();
da1.Fill(FinalUserData);
DataSet datasetfinaluserdata = new DataSet();
datasetfinaluserdata.Tables.Add(FinalUserData);
conn.Close();
da1.Dispose();
USER_TABLE.DataSource = datasetfinaluserdata;
USER_TABLE.DataBind();
USER_TABLE.Rows[0].Visible = false;
}
else
{
if (USER_TABLE.Rows.Count == 0)
{
renderEmptyGridView(USER_TABLE, "BS_ID, BS_NAME_CHT, BS_NAME_ENG, BS_NAME, BS_INSERTOR, BS_INSERT_TIME, BS_EDITOR, BS_EDIT_TIME, BS_LEAVE");
}
}
}
}
public static void renderEmptyGridView(GridView EmptyGridView, string FieldNames)
{
DataTable dTable = new DataTable();
char[] delimiterChars = { ',' };
string[] colName = FieldNames.Split(delimiterChars);
foreach (string myCol in colName)
{
DataColumn dColumn = new DataColumn(myCol.Trim());
dTable.Columns.Add(dColumn);
}
DataRow dRow = dTable.NewRow();
foreach (string myCol in colName)
{
dRow[myCol.Trim()] = DBNull.Value;
}
dTable.Rows.Add(dRow);
EmptyGridView.DataSourceID = null;
EmptyGridView.DataSource = dTable;
EmptyGridView.DataBind();
EmptyGridView.Rows[0].Visible = false;
}
but when I run the web, the error pop up said, "Specified cast is not valid."
I think is it the foreach() is string but in the database the "BS_LEAVE" is a Boolean?
How can I solve it ? Thank You

Image is not displaying from the MySql Database using Asp.Net

I want to add the image to the database and display it in the grid view when it is added successfully. I coded everything, but when I add the details and press save the image is not displayed in the web page. I've attached screen shot for reference.
Here is the code that I used
.aspx code
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2">
<h2>Employee Details</h2>
</td>
</tr>
<tr>
<td>ID</td>
<td><asp:TextBox ID="txtID" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Name</td>
<td><asp:TextBox ID="txtName" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>BloodGroup</td>
<td><asp:TextBox ID="txtBloodGroup" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Emergency Contact No.</td>
<td><asp:TextBox ID="txtContactNo" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Photo:</td>
<td><asp:FileUpload ID="fileuploadEmpImage" runat="server" Width="180px" /></td>
</tr>
<tr>
<td colspan="2"><asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Blood Group" DataField="BloodGroup" />
<asp:BoundField HeaderText="Phone No" DataField="PhoneNo" />
<asp:BoundField HeaderText="Image" DataField="Image" Visible="false" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "EmployeeImageHandler.ashx?Id="+ Eval("Id") %>'
Height="150px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
namespace Image_upload
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridData();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fileuploadEmpImage.HasFile)
{
int length = fileuploadEmpImage.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileuploadEmpImage.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
int id = Convert.ToInt32(txtID.Text);
string name = txtName.Text;
string bloodGroup = txtBloodGroup.Text;
string phoneNo = txtContactNo.Text;
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
connection.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO database.employee (Id,Name,BloodGroup,PhoneNo,ImageI)" + "values('"+ txtID.Text +"', '"+ txtName.Text +"', '"+ txtBloodGroup.Text +"', '"+ txtContactNo.Text +"', '"+ fileuploadEmpImage.FileBytes +"')", connection);
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
txtID.Text = string.Empty;
txtName.Text = string.Empty;
txtBloodGroup.Text = string.Empty;
txtContactNo.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Record added successfully')", true);
BindGridData();
}
}
}
private void BindGridData()
{
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
MySqlCommand command = new MySqlCommand("SELECT Id,Name,BloodGroup,PhoneNo,ImageI from database.employee", connection);
MySqlDataAdapter daimages = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
grdEmployee.DataSource = dt;
grdEmployee.DataBind();
}
}
}
handler.ashx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
namespace Image_upload
{
public class Employeeimage_handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["Id"];
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
connection.Open();
MySqlCommand command = new MySqlCommand("select ImageI from database.employee order by ID" + imageid, connection);
MySqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You have an issue in your SQL statement that you use in the ASHX handler. First of all it produces an incorrect SQL statement and secondly it is vulnerable for SQL Injection attacks. See the OWASP Guidance for in depth technical explanation of the issue.
To fix your code introduce MySqlParameters:
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["Id"];
var connection = new MySqlConnection(
ConfigurationManager.ConnectionString["database"]);
connection.Open();
// remove the order by and add a where with a parameter placeholder
var command = new MySqlCommand(
"select ImageI from database.employee where id = #id",
connection);
// setup parameter and add to command
command.Parameters.AddWithValue("#id", imageid);
// execute
MySqlDataReader dr = command.ExecuteReader();
// rest of your code
}
Also move the connection string out of your code to the web.config. See the msdn article Connection Strings and Configuration Files

How to avoid inserting the unwanted values to database?

I want to insert only the selected value but when I save its inserting all the values in database.
In the above database in subject column I want only the subject which has the faculty.But in my database all the subjects are inserting.
I am using boundfield for the subject column in GridView. My code so far`
<asp:GridView ID="Gvassignsubject" runat="server" AutoGenerateColumns="False" OnRowDataBound="Gvassignsubject_RowDataBound">
<Columns>
<asp:BoundField DataField="Subject" HeaderText="subject" SortExpression="subject" />
<asp:TemplateField HeaderText ="Faculty">
<ItemTemplate>
<asp:Label ID ="lblfaculty" runat="server" Text='<%%# Eval("facultyname") %>>' Visible="false"/>
<asp:DropDownList ID="ddlfaculty" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Set Hour">
<ItemTemplate>
<asp:TextBox ID="txthour" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>`
protected void btnsubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
foreach (GridViewRow r in Gvassignsubject.Rows)
{
for (int i = 0; i < Gvassignsubject.Rows.Count; i++)
{
string batch = ddlbatches.SelectedValue;
string subject = r.Cells[0].Text;
DropDownList ddlfaculty = (DropDownList)Gvassignsubject.Rows[i].FindControl("ddlfaculty");
TextBox txthour = (TextBox)Gvassignsubject.Rows[i].FindControl("txthour");
string facultyname = ddlfaculty.SelectedValue;
string sethour = txthour.Text;
con2.Open();
SqlCommand cmd = new SqlCommand("insert into assign (batch,facultyname,sethour,subject)values(#batch,#facultyname,#sethour,#subject)", con2);
cmd.Parameters.AddWithValue("#batch", batch);
cmd.Parameters.AddWithValue("#subject", subject);
cmd.Parameters.AddWithValue("#facultyname", facultyname);
cmd.Parameters.AddWithValue("#sethour", sethour);
cmd.Connection = con2;
cmd.ExecuteNonQuery();
con2.Close();
}
}
}
}
Its adding all the rows regardless because you have no criteria;
for (int i = 0; i < Gvassignsubject.Rows.Count; i++)
{
DropDownList ddlfaculty = (DropDownList)Gvassignsubject.Rows[i].FindControl("ddlfaculty");
string facultyname = ddlfaculty.SelectedValue;
if (!string.Equals(ddlfaculty.SelectedValue, "Please Select"))
{
string batch = ddlbatches.SelectedValue;
string subject = r.Cells[0].Text;
TextBox txthour = (TextBox)Gvassignsubject.Rows[i].FindControl("txthour");
string sethour = txthour.Text;
con2.Open();
SqlCommand cmd = new SqlCommand("insert into assign (batch,facultyname,sethour,subject)values(#batch,#facultyname,#sethour,#subject)", con2);
cmd.Parameters.AddWithValue("#batch", batch);
cmd.Parameters.AddWithValue("#subject", subject);
cmd.Parameters.AddWithValue("#facultyname", facultyname);
cmd.Parameters.AddWithValue("#sethour", sethour);
cmd.Connection = con2;
cmd.ExecuteNonQuery();
con2.Close();
}
}
I believe you have to set default select list item value as null and check for it in your for loop:
for (int i = 0; i < Gvassignsubject.Rows.Count; i++)
{
if(!string.IsNullOrEmpty(ddlfaculty.SelectedValue)) {
...
}
}
You can put a condition that will check the value exist or not in the subject field. You can do this like below :
if(facultyname !="" && facultyname !="Please Select")
{
SqlCommand cmd = new SqlCommand("insert into assign (batch,facultyname,sethour,subject)values(#batch,#facultyname,#sethour,#subject)", con2);
cmd.Parameters.AddWithValue("#batch", batch);
cmd.Parameters.AddWithValue("#subject", subject);
cmd.Parameters.AddWithValue("#facultyname", facultyname);
cmd.Parameters.AddWithValue("#sethour", sethour);
cmd.Connection = con2;
cmd.ExecuteNonQuery();
}
This is considering the condition that the ddlfaculty dropdown
has the Value same as its Text.
Try this
if(ddlfaculty.selectedindex !=-1 )
{
do the insert function
}

Paging in nested gridview webforms

I am having a little trouble with paging in a nested grid view.
When I try to change page I am getting some very strange and unexpected behaviour. Sometimes it will post back but not actually change the page and sometimes it does change the page but not as expected, it is messing with the order so you will have some items from the previous page still.
My markup is as follows:
<asp:GridView
ID="grdImages"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdImages_PageIndexChanging"
OnRowCancelingEdit="grdImages_RowCancelingEdit"
OnRowCommand="grdImages_RowCommand"
OnRowEditing="grdImages_RowEditing"
OnRowUpdating="grdImages_RowUpdating"
OnRowDeleting="grdImages_RowDeleting"
EmptyDataText="No Data Available at this Time"
OnRowDataBound="grdImages_RowDataBound"
DataKeyNames="ProductId">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" runat="server" Text='<%# Eval("ProductId") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdId" runat="server" AppendDataBoundItems="true" >
<asp:ListItem>Select a product</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
<ItemTemplate>
<asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("ImageId") %>' ></asp:Label>
<asp:Label ID="lblMainImgName" runat="server" Text='<%# Eval("ImageName") %>' ></asp:Label> <br />
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="flupEditMain" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
<ItemTemplate>
<asp:GridView ID="grdSupImages"
runat="server" ShowHeader="false" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
OnRowEditing="grdSupImages_RowEditing"
OnRowUpdating="grdSupImages_RowUpdating" AllowPaging="true" PageSize="4"
OnPageIndexChanging="grdSupImages_PageIndexChanging" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="imgSupId" runat="server" Text='<%# Eval("ImgId") %>' ></asp:Label>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:Label ID="imgSupName" runat="server" Text='<%# Eval("ImageName") %>' AssociatedControlID="imgSup"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:CheckBox ID="chkSupImages" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to delete these images?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
My 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.Globalization;
using System.IO;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class Admin_ProductManagement_addProdImage : System.Web.UI.Page
{
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
private string imageDirectory;
protected void Page_Load(object sender, EventArgs e)
{
// ensure images are uploaded to the right folder.
imageDirectory = Path.Combine(
Request.PhysicalApplicationPath, #"Images\ProductImages");
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayMain";
try
{
con.Open(); // try to open the connection
DataSet ds = new DataSet(); // Initializes a new instance of the DataSet class
adapter.Fill(ds, "ProductImages"); // Adds or refreshes rows in the DataSet to match those in the data source using the DataSet and DataTable names
grdImages.DataSource = ds; // sets the gridview datasource
grdImages.DataBind(); // binds data to gridview
// find dropdownlist in the footer row of the gridview
DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");
// call function
lstProducts(prods);
}
catch (Exception err)
{
lblGrdImages.Text = "BindGrid error: " + err.Message + err.Source + err.StackTrace; // display exceptions in label
}
finally
{
con.Close(); // close connection, even if action was unsuccessful.
}
}
protected void BindNestedGrid(int product, GridView grd)
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = product;
// try to connect, fill dataset and close connection. Also catch exceptions.
try
{
con.Open(); // open the connection.
DataSet rds = new DataSet(); // initialize a data set.
adapt.Fill(rds, "ExtraImages"); // fills dataset
grd.DataSource = rds; // assign data source.
grd.DataBind(); // bind data.
}
catch (Exception err)
{
lblGrdImages.Text = "Bind Nested Grid Error: " + err.Message; // catch exceptions.
}
finally
{
con.Close(); // close the db connection
}
}
protected void lstProducts(DropDownList prods)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader;
// define the sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "LstProds";
try
{
con.Open(); // try to connect to db.
reader = cmd.ExecuteReader(); // execut the reader
while (reader.Read())
{
ListItem item = new ListItem(); // create listitem
item.Text = reader["ProductName"].ToString(); // add product name to item text
item.Value = reader["ProductId"].ToString(); // add productId to item value
prods.Items.Add(item); // populate dropdown list.
}
}
catch (Exception err)
{
lblGrdImages.Text = "List Products Error: " + err.Message; // display error message in a label
}
finally
{
con.Close(); // close the connection.
}
}
protected void addMain(int ProdId, string ImgName, string ImgPath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddMain";
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar, 50));
cmd.Parameters["#ImageName"].Value = ImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar, -1));
cmd.Parameters["#ImagePath"].Value = ImgPath;
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProdId;
try
{
con.Open(); // attempt to open the connection
DataSet ds = new DataSet(); // initialize the dataset
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add main error: " + err.Message; // display exceptions in a label control
}
finally
{
con.Close(); // close connection.
}
}
protected void addExtraImages(int ProductId, string ExImgName, string ExImagePath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProductId;
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar,50));
cmd.Parameters["#ImageName"].Value = ExImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar,-1));
cmd.Parameters["#ImagePath"].Value = ExImagePath;
try
{
con.Open(); // try to open db connection
DataSet ds = new DataSet(); // initialize data set.
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add extra images error: " + err.Message; // display exception in a label
}
finally
{
con.Close(); // close the connection
}
}
protected void DeleteProductImages(int Product)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Delete";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = Product;
try
{
con.Open(); // open connection
DataSet ds = new DataSet(); // initialize rthe dataset
adapter.Fill(ds); // fill dataset.
}
catch (Exception err)
{
lblGrdImages.Text = "Delete error: " + err.Message; // report error in a label.
}
finally
{
con.Close(); // close the connection.
}
}
protected void grdImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdImages.PageIndex = e.NewPageIndex; // sets the page index
BindGrid(); // bind the grid.
}
protected void grdImages_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdImages.EditIndex = -1; // sets the page index
BindGrid(); // bind the grid.
}
private bool isValid(HttpPostedFile file, string[] extAry, string ext) // checks extension
{
bool isValid = false;
for (int i = 0; i < extAry.Length; i++)
{
if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)
isValid = true;
}
return isValid;
}
protected void uploadMainImage() {
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain"); // find control
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
string mainFile = Path.GetFileName(main.PostedFile.FileName); // get file name.
string ext = Path.GetExtension(mainFile); // get file extension.
if (isValid(main.PostedFile, validFileTypes, ext)) // check if file extension is valid.
{
if (File.Exists(mainFile)) // check if file exists
{
lblGrdImages.Text = "File with the name: " + mainFile + " already exists. Please rename or choose a different file.";
}
else
{
try
{
string serverFileName = Path.GetFileName(mainFile); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
main.SaveAs(uploadPath); // save file
addMain(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // Call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = err.Message;
}
}
}
}
protected void uploadExtraImages()
{
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra"); // find conrol
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
if (extra.HasFiles)
{
foreach (HttpPostedFile file in extra.PostedFiles)
{
string ext = Path.GetExtension(file.FileName);
if (isValid(file, validFileTypes, ext)) // check file extension
{
string serverFileName = Path.GetFileName(file.FileName); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
try
{
file.SaveAs(uploadPath); // save file
addExtraImages(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = "Error: " + err.Message;
}
}
}
}
}
protected void grdImages_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
// find the required controls in the grdview.
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain");
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra");
if (main.HasFile)
{
uploadMainImage();
if (extra.HasFiles)
{
uploadExtraImages();
}
grdImages.EditIndex = -1;
BindGrid();
}
else
{
lblGrdImages.Text = "Product main image is required.";
}
}
}
protected void grdImages_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (!this.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grd = (GridView)e.Row.FindControl("grdSupImages"); // find controls
Label prodId = (Label)e.Row.FindControl("lblProdId");
int product = Convert.ToInt32(prodId.Text); // assign values to variables.
BindNestedGrid(product, grd); // call the function.
}
}
}
protected void grdImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// find controls
Label product = (Label)grdImages.Rows[e.RowIndex].FindControl("lblProdId");
Label image = (Label)grdImages.Rows[e.RowIndex].FindControl("lblMainImgName");
GridView grd = (GridView)grdImages.Rows[e.RowIndex].FindControl("grdSupImages");
// declare variables and assign values
int prodid = Convert.ToInt32(product.Text);
string path = Server.MapPath(#"~\Images\ProductImages\" + image.Text);
File.Delete(path);
foreach(GridViewRow row in grd.Rows)
{
Label img = (Label)row.FindControl("imgSupName");
string imgName = img.Text;
string imgPath = Server.MapPath(#"~\Images\ProductImages\" + imgName);
try
{
File.Delete(imgPath);
}
catch (Exception err)
{
lblGrdImages.Text = "File Delete Error: " + err.Message + "<br />" + err.InnerException + "||" + err.StackTrace;
}
}
DeleteProductImages(prodid);
grdImages.EditIndex = -1;
BindGrid();
}
protected void grdImages_RowEditing(object sender, GridViewEditEventArgs e)
{
grdImages.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void grdSupImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
}
}
I would be eternally grateful of any assistance with this matter. If you require any further information please let me know and I will provide.
Although nobody wanted to help me, I have found the answer to my problem.
I thought id share this information as it may be able to help somebody else.
This is what I came up with for my child gridview pageindexchanging event:
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
BindNestedGrid(Convert.ToInt32(gv.ToolTip), gv);
}

Categories