how to display image from sql table in gridview? - c#

hi i tried to display image from sql table to gridview but its not displaying this is my code to bind gridview with sql table records.....
When the user login , the user login photo should display thats y i am trying
the image already stored in database but there is an ISSUE to retrive the image from database to gridview
PostBookChat.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblsession.Text = "Welcome" + Convert.ToString(Session["UName"]);
sessionimage();
}
}
private void sessionimage()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
try
{
int EmpID = (int)Session["EmpID"];
SqlDataAdapter Adp = new SqlDataAdapter("select EmpID,Photo from TBL_PBLogin where EmpID='" + EmpID + "'", con);
DataTable Dt = new DataTable();
con.Open();
Adp.Fill(Dt);
gridviewphoto.DataSource = Dt;
gridviewphoto.DataBind();
con.Close();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
PostBookChat.aspx
<body>
<form id="form1" runat="server">
<div>
<div id="header">
<img src="Image/book.png" height="60" width="140" style ="margin-left:0px;float:left;"/>
<div id="login">
<b><asp:Label ID="lblsession" runat="server" ForeColor="white" CssClass="label"></asp:Label>
<asp:GridView ID="gridviewphoto" runat="server" AutoGenerateColumns="false" BackColor="#CC3300" ForeColor="Black" ShowHeader="false" GridLines="None">
<Columns>
<asp:TemplateField ControlStyle-Width="100" ControlStyle-Height="100">
<ItemTemplate>
<asp:Image ID="Image" runat="server" ImageUrl='<%# "~/Handler.ashx?id=" + Eval("EmpID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnlogout" runat="server" Text="Sign Out" CssClass="myButton" OnClick="btnlogout_Click"/>
</div>
</div>
</body>
Handler.ashx
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["EmpID"] == null) return;
string connStr = ConfigurationManager.AppSettings["connect"].ToString();
string pictureId = context.Request.QueryString["EmpID"];
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Photo FROm TBL_PBLogin WHERE EmpID = #EmpId", conn))
{
cmd.Parameters.Add(new SqlParameter("#EmpID", pictureId));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Photo")]);
reader.Close();
}
}
}
}
DataBase
EmpID (PK,int notnull) (1,1)
UName(varchar(255),notnull)
Password(varchar(255),notnull)
Photo(image,null)

Related

OnRowUpdating does not work even if i have a !postback in page_load

I am a beginner and I am creating a crud webpage in asp.net and i can't get the update(save) button working. here is the snippet of my code:
Save and Cancel buttons in Main.aspx
<div height: 334px;" class="gridview">
<asp:GridView ID="RetailInfoGridView"
AutoGenerateColumns="False"
ShowFooter="true"
DataKeyNames="StockKeepingID"
runat="server"
ShowHeaderWhenEmpty="True"
HeaderStyle-ForeColor="White"
AlternatingRowStyle="alt"
EmptyDataText="No Records Found"
AllowSorting="True"
OnRowCommand="RetailInfoGridView_RowCommand"
OnDataBound="RetailInfoGridView_DataBound"
OnRowDataBound="RetailInfoGridView_RowDataBound"
OnRowEditing="RetailInfoGridView_RowEditing"
OnRowCancelingEdit="RetailInfoGridView_RowCancelingEdit"
OnRowUpdating="RetailInfoGridView_RowUpdating"
onRowDeleting="RetailInfoGridView_RowDeleting"
OnSelectedIndexChanged="RetailInfoGridView_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Edit" CommandName="Edit" runat="server" Text="Edit" ToolTip="Edit" />
<asp:Button ID="Delete" CommandName="Delete" runat="server" Text="Delete" ToolTip="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="Save" CommandName="Save" runat="server" Text="Save" ToolTip="Save" />
<asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="Add" CommandName="Add" runat="server" Text="Add" ToolTip="Add" />
</FooterTemplate>
</asp:TemplateField>
<EditItemTemplate>
<asp:Button ID="Save" CommandName="Save" runat="server" Text="Save" ToolTip="Save" />
<asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>
...
Main.aspx.cs
string connectionString = "Data Source=102000-LSU-2216;Initial Catalog=loginDB;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateGridView();
}
}
protected void SearchTextBox_TextChanged(object sender, EventArgs e)
{
/* connect.Open();
string query = "SELECT * FROM RetailInfo WHERE StockKeepingUnit LIKE '%" + SearchTextBox.Text + "%'";
adapter = new SqlDataAdapter(query, connect);
table = new DataTable();
adapter.Fill(table);
RetailInfoGridView.DataSource = table;
RetailInfoGridView.DataBind();
connect.Close();*/
}
protected void SearchButton_Click(object sender, EventArgs e)
{
using (SqlConnection connect = new SqlConnection(connectionString))
{
connect.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM RetailInfo WHERE StockKeepingUnit LIKE '%" + SearchTextBox.Text + "%'", connect);
DataTable table = new DataTable();
adapter.Fill(table);
RetailInfoGridView.DataSource = table;
RetailInfoGridView.DataBind();
}
}
protected void RetailInfoGridView_DataBound(object sender, EventArgs e)
{
}
protected void RetailInfoGridView_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void RetailInfoGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
e.Row.ToolTip = "Click the link to view Description";
//e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(RetailInfoGridView, "Select$" + e.Row.RowIndex);
}
}
void PopulateGridView()
{
using (SqlConnection connect = new SqlConnection(connectionString))
{
connect.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM RetailInfo", connect);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
{
RetailInfoGridView.DataSource = table;
RetailInfoGridView.DataBind();
}
else
{
table.Rows.Add(table.NewRow());
RetailInfoGridView.DataSource = table;
RetailInfoGridView.DataBind();
RetailInfoGridView.Rows[0].Cells.Clear();
RetailInfoGridView.Rows[0].Cells.Add(new TableCell());
RetailInfoGridView.Rows[0].Cells[0].ColumnSpan = table.Columns.Count;
RetailInfoGridView.Rows[0].Cells[0].Text = "No record Found";
}
}
}
protected void RetailInfoGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("Add"))
{
using (SqlConnection connect = new SqlConnection(connectionString))
{
connect.Open();
string query = "INSERT INTO RetailInfo(StockKeepingUnit,UniversalProductCode,VendorName,ProductName,ProductDesc,RetailPrice) VALUES (#StockKeepingUnit,#UniversalProductCode,#VendorName,#ProductName,#ProductDesc,#RetailPrice)";
SqlCommand command = new SqlCommand(query, connect);
command.Parameters.AddWithValue("#StockKeepingUnit", (RetailInfoGridView.FooterRow.FindControl("skuTextBoxFooter") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#UniversalProductCode", (RetailInfoGridView.FooterRow.FindControl("upcTextBoxFooter") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#VendorName", (RetailInfoGridView.FooterRow.FindControl("vnTextBoxFooter") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#ProductName", (RetailInfoGridView.FooterRow.FindControl("pnTextBoxFooter") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#ProductDesc", (RetailInfoGridView.FooterRow.FindControl("pdTextBoxFooter") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#RetailPrice", (RetailInfoGridView.FooterRow.FindControl("rpTextBoxFooter") as TextBox).Text.Trim());
command.ExecuteNonQuery();
PopulateGridView();
ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('New Record Added');", true);
}
}
}
catch (Exception ex)
{
}
}
protected void RetailInfoGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
RetailInfoGridView.EditIndex = e.NewEditIndex;
PopulateGridView();
}
protected void RetailInfoGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
RetailInfoGridView.EditIndex = -1;
PopulateGridView();
}
protected void RetailInfoGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
using (SqlConnection connect = new SqlConnection(connectionString))
{
connect.Open();
string query = "UPDATE RetailInfo SET StockKeepingUnit=#StockKeepingUnit,UniversalProductCode=#UniversalProductCode,VendorName=#VendorName,ProductName=#ProductName,ProductDesc=#ProductDesc,RetailPrice=#RetailPrice WHERE StockKeepingID=#id";
SqlCommand command = new SqlCommand(query, connect);
command.Parameters.AddWithValue("#StockKeepingUnit", (RetailInfoGridView.Rows[e.RowIndex].FindControl("skuTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#UniversalProductCode", (RetailInfoGridView.Rows[e.RowIndex].FindControl("upcTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#VendorName", (RetailInfoGridView.Rows[e.RowIndex].FindControl("vnTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#ProductName", (RetailInfoGridView.Rows[e.RowIndex].FindControl("pnTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#ProductDesc", (RetailInfoGridView.Rows[e.RowIndex].FindControl("pdTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#RetailPrice", (RetailInfoGridView.Rows[e.RowIndex].FindControl("rpTextBox") as TextBox).Text.Trim());
command.Parameters.AddWithValue("#id", Convert.ToInt32(RetailInfoGridView.DataKeys[e.RowIndex].Value.ToString()));
command.ExecuteNonQuery();
RetailInfoGridView.EditIndex = -1;
PopulateGridView();
ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('Record Updated');", true);
}
}
catch (Exception ex)
{
}
}
protected void RetailInfoGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
using (SqlConnection connect = new SqlConnection(connectionString))
{
connect.Open();
string query = "DELETE FROM RetailInfo WHERE StockKeepingID = #id";
SqlCommand command = new SqlCommand(query, connect);
command.Parameters.AddWithValue("#id", Convert.ToInt32(RetailInfoGridView.DataKeys[e.RowIndex].Value.ToString()));
command.ExecuteNonQuery();
PopulateGridView();
ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('Record Deleted');", true);
}
}
catch (Exception ex)
{
}
}
Whenever I run the program, I edit values to a specific row and then I click the save button, it does not do anything. I have read other answers that said to have a !postback and DataKeyNames in the code but I already have the postback in Main.aspx.cs and the DataKeyNames on Main.aspx. I don't know if the error comes on the .aspx or on the .aspx.cs. Have I done something wrong on the code? any help would be highly appreciated. Thank you.
UPDATE:
I have solved the problem. instead of writing "save" variables:
<EditItemTemplate>
<asp:Button ID="Save" CommandName="Save" runat="server" Text="Save" ToolTip="Save" />
<asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>
I changed it to "update":
<EditItemTemplate>
<asp:Button ID="Update" CommandName="Update" runat="server" Text="Update" ToolTip="Update" />
<asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>
Although I do not know why it worked, but it did the job!
If you know why "save" did not work and and "update" worked, I would really appreciate it if you tell me so i can be enlightened.
Thank you for all who helped.

how to bind two columns of a database table up and down as a single column in data gridview

how to bind two columns of a database table UP and DOWN as a single column in data gridview.
Kindly help me.
.ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<span>Merged cell</span>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblMergedField" runat="server" Text='<%# Eval("ID") + " - " + Eval("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindData();
}
private void BindData()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("SELECT ID,City FROM Cities", con))
{
using (var adapter = new SqlDataAdapter(command))
{
con.Open();
var table = new DataTable();
adapter.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
con.Close();
}
}
}
}
Output:

Why does the GridView disappear after a button click

<asp:UpdatePanel ID="upExec" runat="server" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<button type="button" runat="server" id="btnExec" onserverclick="btnExec_Click" class="btnAll btnExec">Execute SQL Job</button>
<asp:Label ID="lblEMsg" runat="server" ClientIDMode="Static" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="upGV" runat="server" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView EmptyDataText="No Provider Exists" ID="gvData" runat="server" ClientIDMode="Static" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderStyle-Width="5%" DataField="Name" HeaderText="Name" />
<asp:BoundField HeaderStyle-Width="5%" DataField="ID" HeaderText="ID" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
if (!Page.IsPostBack)
{
ViewState["sortOrder"] = "Asc";
ViewState["sortExp"] = "Due Date";
ShowGridView("Name", "Asc");
}
public void ShowGridView(string sortExp, string sortDir)
{
using (SqlConnection sc = new SqlConnection(gloString))
{
try
{
sc.Open();
SqlDataAdapter sda = new SqlDataAdapter(strQuery, sc);
DataSet ds = new DataSet();
sda.Fill(ds);
DataView dv = new DataView();
dv = ds.Tables[0].DefaultView;
gvData.DataSource = dv;
gvData.DataBind();
}
catch (SqlException)
{
}
finally
{
sc.Close();
}
}
upGV.Update();
}
public void btnExec_Click(object sender, EventArgs e)
{
using (SqlConnection sc = new SqlConnection(gloString))
{
try
{
sc.Open();
using (SqlCommand scd = new SqlCommand())
{
scd.CommandText = "MySP";
scd.CommandType = CommandType.StoredProcedure;
scd.Connection = sc;
scd.ExecuteNonQuery();
}
}
catch (SqlException)
{
}
finally
{
sc.Close();
}
}
using (SqlConnection sc = new SqlConnection(floString))
{
try
{
sc.Open();
SqlCommand scd = new SqlCommand();
scd.CommandType = CommandType.StoredProcedure;
scd.Connection = sc;
scd.CommandText = "msdb.dbo.sp_start_job";
scd.Parameters.AddWithValue("#job_name", "JobName");
using (scd)
{
scd.ExecuteNonQuery();
ShowGridView("Name", "Asc");
}
}
catch (SqlException)
{
}
finally
{
sc.Close();
}
}
upExec.Update();
}
When the page first loads, I can see the GridView. When I click the btnExec, the GridView disappears and it displays "No Provider Exists". When I check the source of the page the data is still there.
How can I resolve it so when the button is clicked, it performs the stored procedure and reloads the GridView with the new data.
Looks like you should move the call to ShowGridView() in your btnExec_Click() method to outside the outer "using" statement, right before the call to upExec.Update().
On my case, I had to add this attribute to the panel that was wrapping my GridView to keep it visible and working, every time I was clicking on a row to select it, it kept disappearing :
<asp:Panel EnableViewState="True">

Dynamically Populating text boxes from drop down not working

I am trying to get two text boxes to populate when a drop down list has it's value selected (and I want the data in the text boxes to change when the selection is changed without the page reloading), I wrote some code compiling what I have gathered from other questions like this, but for some reason its just not working here is my CS.
public partial class UsersFormPage : Page
{
protected void userddlistedit_SelectedIndexChanged(object sender, EventArgs e)
{
FillBoxes(userddlistedit.SelectedValue);
}
private void FillBoxes(string HR_ID)
{
// Create a new dataset object
DataSet dt = new DataSet();
// Create SqlConnection
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=SQL2008R2SRV;Initial Catalog=employeetrainingtracking;Integrated Security=True";
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
// Set the connection on the sql command object
cmd.Connection = conn;
cmd.CommandText = "select * from users where HR_ID='" + HR_ID + "'";
using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
{
adap.Fill(dt);
}
}
}
if (dt.Tables[0].Rows.Count > 0)
{
usernameedit.Text = dt.Tables[0].Rows[0]["Username"].ToString(); //Where column name us the Fields for your Table that you wanted to display in the TextBoxes
passwordedit.Text = dt.Tables[0].Rows[0]["Password"].ToString();
}
}
}
And here is the part of my page it affects:
<li class="form-row text-row">
<label>User:</label>
<asp:DropDownList ID="userddlistedit" runat="server" CssClass="text-input-dds" DataSourceID="personnelsql" DataTextField="HR_ID" DataValueField="HR_ID" AutoPostBack="True" OnSelectedIndexChanged="userddlistedit_SelectedIndexChanged" />
</li>
<li class="form-row text-input-row">
<label>Username:</label>
<asp:TextBox name="usernameedit" type="text" class="text-input-lg required" id="usernameedit" runat="server" AutoPostBack="True" />
</li>
<li class="form-row text-input-row">
<label>Password:</label>
<asp:TextBox name="passwordedit" type="text" class="text-input-lg required" id="passwordedit" runat="server" AutoPostBack="True" />
</li>
I cannot seem to figure out why its not working.
This is the data source for my drop down list:
<asp:SqlDataSource ID="personnelsql" runat="server"
ConnectionString="<%$ ConnectionStrings:employeetrainingtrackingConnectionString %>"
SelectCommand="SELECT * FROM personnel ORDER BY HR_ID">
</asp:SqlDataSource>
I figured out what I was missing, so I am posting the code below so people can use it:
Here is the code that goes on the CS page:
protected void userddlistedit_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM users ";
selectSQL += "WHERE HR_ID='" + userddlistedit.SelectedItem.Value + "'";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
usernameedit.Text = reader["Username"].ToString();
passwordedit.Text = reader["Password"].ToString();
accessleveledit.SelectedValue = reader["AccessLevel"].ToString();
reader.Close();
lblResults.Text = "";
}
finally
{
con.Close();
}
}
This is the code in the actual aspx page, I added two things:
-I added the DropDownExtender
-I added the triggers (after the but before the tag
<li class="form-row text-row">
<label>User:</label>
<asp:DropDownList ID="userddlistedit" runat="server" CssClass="text-input-dds" AutoPostBack="True" OnSelectedIndexChanged="userddlistedit_SelectedIndexChanged"></asp:DropDownList>
</li>
<li class="form-row text-input-row">
<label>Username:</label>
<asp:TextBox name="usernameedit" type="text" class="text-input-lg required" id="usernameedit" runat="server"></asp:TextBox>
<asp:DropDownExtender ID="ExtenderUserEdit" DropDownControlID="userddlistedit" Enabled="true" TargetControlID="usernameedit" runat="server"></asp:DropDownExtender>
<asp:RequiredFieldValidator runat="server" ID="ValidateUsernameEdit" ControlToValidate="usernameedit" ErrorMessage="Username is required" Display="dynamic" ValidationGroup="EditSection">*</asp:RequiredFieldValidator>
</li>
<li class="form-row text-input-row">
<label>Password:</label>
<asp:TextBox name="passwordedit" type="text" class="text-input-lg required" id="passwordedit" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="ValidatePasswordEdit" ControlToValidate="passwordedit" ErrorMessage="Password is required" Display="dynamic" ValidationGroup="EditSection">*</asp:RequiredFieldValidator>
</li>
.....
<Triggers>
<asp:AsyncPostBackTrigger ControlID="userddlistedit" EventName="SelectedIndexChanged" />
</Triggers>
I also changed the way I got my data for the drop down list to the following (added in the CS page):
private void UsersListDD()
{
userddlist.Items.Clear();
userddlistedit.Items.Clear();
userddlistdelete.Items.Clear();
string selectSQL = "SELECT * FROM personnel";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["FirstName"] + " " + reader["LastName"];
newItem.Value = reader["HR_ID"].ToString();
userddlist.Items.Add(newItem);
userddlistedit.Items.Add(newItem);
userddlistdelete.Items.Add(newItem);
}
reader.Close();
}
finally
{
con.Close();
}
}
Hopefully, this helps someone.

asp.net DataList select DropDownList value

I am making an application about article publication. I have 2 tables
"artikulli"
id int Unchecked
tema varchar(250) Checked
abstrakti text
data_publikimit date
path varchar(350)
keywords varchar(350)
kategoria_id int
departamenti_id int
"kategorite"
id int Unchecked
emertimi varchar(350)
I want to display in a dropdown list all values of field "emertimi" and when the user selects one value to save id of that value in table "artikulli".
I have done the following, but I have the problem with syntax because I am using DATALIST.
public partial class AddArticle : System.Web.UI.Page
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
try
{
if (!IsPostBack)
{
Bind();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
public void Bind()
{
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
protected void datalist2_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
TextBox txtAbstrakti = e.Item.FindControl("txtAbstrakti") as TextBox;
TextBox txtData = e.Item.FindControl("txtData") as TextBox;
TextBox txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection conn = new SqlConnection(connection);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "Insert into artikulli(tema,abstrakti,data_publikimit,path,keywords,kategoria_id) values (#tema,#abstrakti,#data,#filename,#keywords,#kategoria)";
command.Parameters.Add(new SqlParameter("#tema", txtTema.Text));
command.Parameters.Add(new SqlParameter("#abstrakti", txtAbstrakti.Text));
command.Parameters.Add(new SqlParameter("#data", txtData.Text));
command.Parameters.Add(new SqlParameter("#keywords", txtKeywords.Text));
command.Parameters.Add(new SqlParameter("#kategoria", drpdKategoria.SelectedValue));
FileUpload FileUploadArtikull = (FileUpload)e.Item.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise se file qe lejohet eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("#filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni ngarkuar asnje artikull');", true);
}
}
}
AddArtikull.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddArtikull.aspx.cs" Inherits="AddArticle" MasterPageFile="~/MasterPage2.master" %>
<asp:Content ID="content2" ContentPlaceholderID=ContentPlaceHolder2 runat="server">
<asp:DataList ID="datalist2" runat="server"
onitemcommand="datalist2_ItemCommand" >
<FooterTemplate>
<section id="main" class="column" runat="server" style="width:900px;">
<article class="module width_full" style="width:900px;">
<header><h3 style="text-align: center">Shto Artikull </h3></header>
<div id="Div1" class="module_content" runat="server">
<asp:Label ID="Label1" runat="server" style="font-weight: 700">Tema</asp:Label>
<fieldset>
<asp:TextBox ID="txtTema" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTema" runat="server"
ControlToValidate="txtTema" Display="Dynamic"
ErrorMessage="Kjo fushe eshte e nevojshme" style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset><br />
<asp:Label ID="Label6" runat="server" style="font-weight: 700">Abstrakti</asp:Label>
<fieldset>
<asp:TextBox ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorAbstrakti" runat="server"
ControlToValidate="txtAbstrakti" ErrorMessage="Kjo fushe eshte e nevojshme"
style="color: #CC0000"></asp:RequiredFieldValidator>
</fieldset>
<asp:Label ID="lblData" runat="server" style="font-weight: 700">Data e Publikimit</asp:Label>
<fieldset>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="lblKeywords" runat="server" style="font-weight: 700">Keywords</asp:Label>
<fieldset>
<asp:TextBox ID="txtKeywords" runat="server"></asp:TextBox>
</fieldset>
<br />
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<div>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Insert"
/>
</div><br />
<strong>Ngarko Artikull</strong><br />
<asp:FileUpload ID="FileUploadArtikull" runat="server" /><br />
<br />
<asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
</div>
</article>
</section>
</FooterTemplate>
</asp:DataList>
</asp:Content>
It shows this error:
Compiler Error Message: CS0103: The name 'e' does not exist in the
current context
In this line:
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
In your bind method you are calling an object e that doesn't exist. If the dropdownlist isn't inside a bound element, you can just reference the front code directly, e.g.
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id"; // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();
without finding the control as long as it is runat="server"
UPDATE
Okay, so you need to add an OnItemCreated event in your datalist
OnItemCreated="datalist2_OnItemCreated"
Then in that method you need this
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection)
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
That will work for if you only have the footer, if you add an itemtemplate then you just need to get rid of the check for the footer and on each item creation grab that dropdownlist for that item

Categories

Resources