ListView Rendering image issue. [duplicate] - asp.net

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Rendering bytes from sql server to an image control?
<asp:ListView ID="lvGallery" runat="server" DataSourceID="SqlDataSource1">
<LayoutTemplate>
<table runat="server" id="tableGallery">
<tr runat="server" id="itemPlaceHolder">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr><td>
<div class="box_img2">
<div class="g_size">
<a runat="server" id="linkImage"><img id="Image1" runat="server" src="MyImage.jpg" /></a>
</div>
</div>
</td></tr>
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=CHANDAN-PC;Initial Catalog=Metamorphism;User ID=sa;password=chandan;"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [Image] FROM [GalleryImages]"></asp:SqlDataSource>
public void ProcessRequest(HttpContext context)
{
//write your handler implementation here.
string username = Convert.ToString(context.Request.QueryString["username"]);
if (username != null)
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
byte[] arrContent;
DataRow dr;
string strSql;
strSql = "Select Image from GalleryImages where username = '" + username + "'";
da = new SqlDataAdapter(strSql, connection.ConnectionString);
da.Fill(ds);
dr = ds.Tables[0].Rows[0];
arrContent = (byte[])dr["ImageFile"];
context.Response.ContentType = "jpeg";
context.Response.OutputStream.Write(arrContent, 0, arrContent.Length);
context.Response.End();
}
}
I have added httphandlers tag in web.config.

I think you need to change this
<div class="box_img2">
<div class="g_size">
<a runat="server" id="linkImage">
<img id="Image1" runat="server" src='<%# Eval( HttpContext.Current.Request.QueryString["username"] ,"YourGenericHandler.ashx?username={0}") %>' /></a>
</div>
</div>

Related

ASP.NET Edit a Field without reloading the whole Listview

I have a Listview and a dropdownlist:
<asp:ListView ID="lv_ClassTeacher" runat="server" vertical-align="top" OnSelectedIndexChanged="lv_ClassTeacher_SelectedIndexChanged" OnSelectedIndexChanging="lv_ClassTeacher_SelectedIndexChanging" DataKeyNames ="ClassID" OnPagePropertiesChanged="lv_ClassTeacher_PagePropertiesChanged" OnPagePropertiesChanging="lv_ClassTeacher_PagePropertiesChanging" OnItemDataBound="lv_ClassTeacher_ItemDataBound" OnItemCommand="lv_ClassTeacher_ItemCommand">
<LayoutTemplate>
<table border="1">
<tr runat="server">
<th runat="server"></th>
<th runat="server">Class</th>
<th runat="server">Teacher</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:Button ID="cmd_View" runat="server" CommandName="Select" Text="View" Height="21px" /></td>
<td><div runat="server" id="area"><asp:Label ID="Label1" runat="server" Text='<%#Eval("Class") %>' /></div></td>
<td><asp:Label ID="Label2" runat="server" Text='<%#Eval("Teacher") %>' /></td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:DropDownList ID="cb_SwitchTeacher" runat="server" AutoPostBack = "true" OnSelectedIndexChanged="cb_SwitchTeacher_SelectedIndexChanged">
Part of code behind:
conn.Open();
using (MySqlCommand sqlCommand = conn.CreateCommand())
{
sqlCommand.CommandText = "SELECT * FROM tblClassTeacher";
using (MySqlDataAdapter sda = new MySqlDataAdapter(sqlCommand))
{
DataTable dt = new DataTable();
sda.Fill(dt);
lv_ClassTeacher.DataSource = dt;
lv_ClassTeacher.DataBind();
}
}
protected void cb_SwitchTeacher_SelectedIndexChanged(object sender, EventArgs e)
{
string TeacherName= cb_SwitchLabel.Text;
using (MySqlCommand sqlCommand = conn.CreateCommand())
{
sqlCommand.CommandText = "UPDATE tblClassTeacher SET Teacher=" + TeacherName + " WHERE ClassID=" + lv_ClassTeacher.SelectedDataKey.Value.ToString();
sqlCommand.ExecuteNonQuery();
//What can I do to update the listview without reloading the whole table?
}
}
}
On Pressing the "cmd_View", the Class field will be highlighted. When user switch to another Teacher on the dropdownlist, I will update the database.
But I want to update the listview as well without reloading the whole table.
Can I do that? Thank you.

Text not getting inserted into table, but only auto incrementing other column

I have multiple textboxes that goes into a table called dbo.skills
dbo.Skills SkillID (PK- AutoIncrement) | SkillName
So when I used this method, the name is not getting stored but only SkillID is getting auto-incremented. Here is my .cs code
public void InsertSkillInfo()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
try
{
for (int i = 1; i <= 4; i++)
{
conn.Open();
//string skill = (TextBox)((Page.FindControl("TextBox" + i.ToString()))).Text;
var skill = "";
var control = Page.FindControl("TextBox" + i.ToString()) as TextBox;
if (control != null)
{
skill = control.Text;
}
const string sqlStatement = "INSERT INTO Skills (SkillName) VALUES (#SkillName)";
SqlCommand cmd = new SqlCommand(sqlStatement, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#SkillName", skill);
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
After entering values in textboxes, table looks like this-
Dbo.Skills
SkillID | SkillName
1 |
2 |
3 |
4 |
ASPX code:
<asp:Label ID="Label1" class="caption" runat="server" Text="Skill Name"></asp:Label>
<asp:TextBox ID="TextBox1" class="box" runat="server"></asp:TextBox> <br /> <br />
<asp:Label ID="Label2" class="caption" runat="server" Text="Skill Name"></asp:Label>
<asp:TextBox ID="TextBox2" class="box" runat="server"></asp:TextBox> <br /> <br />
<asp:Label ID="Label3" class="caption" runat="server" Text="Skill Name"></asp:Label>
<asp:TextBox ID="TextBox3" class="box" runat="server"></asp:TextBox> <br /> <br />
<asp:Button ID="Button1" class="box" runat="server" Text="Insert"
onclick="Button1_Click" /> <br /><br /><br />

Cannot Bind my Listview

I want to bind my Listview but I can't. I dont know what I am doing wrong here. When I press ctrl+f5, the page is empty.
My Code is:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Student_ID">
<LayoutTemplate>
<table id="itemplaceholderContainer" runat="server">
<tr id="itemplaceholder">
<td>
Student ID :
</td>
<td>
Registration Number :
</td>
<td>
Student Name :
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
StudentID:
<asp:Label ID="LabelID" runat="server" Text='<%Eval("Student_ID") %>'></asp:Label>
StudentRegistrationNumber:<asp:Label ID="LabelNumber" runat="server" Text='<%Eval("StudentRegistrationNumber") %>'></asp:Label>
StudentName:<asp:Label ID="LabelName" runat="server" Text='<%Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:ListView>
</asp:Content>
Codebehind is :
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=LOCALHOST;Initial Catalog=ITCF;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Student", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.fill(dt);
ListView1.DataSource = dt;
ListView1.DataBind();
}
try this:
first your item template is worng, and also you need to fill the data adabter form the Data Table
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Student_ID">
<LayoutTemplate>
<table id="itemplaceholderContainer" runat="server">
<tr id="itemplaceholder">
<td>
Student ID :
</td>
<td>
Registration Number :
</td>
<td>
Student Name :
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
StudentID:
<asp:Label ID="LabelID" runat="server" Text='<%# Eval("Student_ID") %>'></asp:Label>
StudentRegistrationNumber:<asp:Label ID="LabelNumber" runat="server" Text='<%# Eval("StudentRegistrationNumber") %>'></asp:Label>
StudentName:<asp:Label ID="LabelName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:ListView>
</asp:Content>
Codebehind is :
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=LOCALHOST;Initial Catalog=ITCF;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Student", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ListView1.DataSource = dt;
ListView1.DataBind();
}
The last 3 lines of code in your code-behind tell the whole story:
DataTable dt = new DataTable();
ListView1.DataSource = dt;
ListView1.DataBind();
You're instantiating a new, empty DataTable and binding ListView1 to it. Thus, behaving correctly and exactly as designed, your ListView is displaying zero records from the empty DataTable.
You'll want to fetch the data from the DataAdapter before you bind anything to it. Something like this:
var students = new DataSet();
da.Fill(students, "Student");
if (students.Tables.Count == 1)
{
ListView1.DataSource = students.Tables[0];
ListView1.DataBind();
}
Note: There may be a more direct way to fetch the DataTable. I haven't worked with DataSets and DataTables in a long time, but .Fill() may be able to directly use a DataTable and skip my checking of a valid table in the DataSet above.)
Your datatable is never getting populated. Have a look at the following:
http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx

GridView isn't reflecting AJAX changes

I'm using AJAX right now to update my GridView when I search for a string of text in the gridview, or when I select from a dropdownlist what I want to order the Gridview by. This was working previously, but I had really messy code. So I've cleaned it up a little bit, added some parameters and such. Unfortunately, now, when the selectedindex of the dropdownlist is changed or when someone tries to search for a field, nothing happens - the page just refreshes. I'm also getting an exception saying "The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name".
If you need to see any more code then please let me know!
public vieworders()
{
this.PreInit += new EventHandler(vieworders_PreInit);
}
void vieworders_PreInit(object sender, EventArgs e)
{
orderByString = orderByList.SelectedItem.Value;
fieldString = searchTextBox.Text;
updateDatabase(fieldString, orderByString);
}
protected void updateDatabase(string _searchString, string _orderByString)
{
string updateCommand = "SELECT fName,lName,zip,email,cwaSource,price,length FROM SecureOrders WHERE fName LIKE #searchString OR lName LIKE #searchString OR zip LIKE #searchString OR email LIKE #searchString OR cwaSource LIKE #searchString OR length LIKE #searchString OR price LIKE #searchString ORDER BY #orderByString";
Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Cabot3");
ConnectionStringSettings connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];
// Create an SqlConnection to the database.
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
using (SqlCommand _fillDatabase = new SqlCommand(updateCommand, connection))
{
connection.Open();
_fillDatabase.Parameters.Add("#searchString", SqlDbType.VarChar, 50).Value = _searchString;
_fillDatabase.Parameters.Add("#orderByString", SqlDbType.VarChar, 50).Value = _orderByString;
_fillDatabase.ExecuteNonQuery();
dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);
// create the DataSet
dataSet = new DataSet();
// fill the DataSet using our DataAdapter
dataAdapter.Fill(dataSet, "SecureOrders");
DataView source = new DataView(dataSet.Tables[0]);
DefaultGrid.DataSource = source;
DefaultGrid.DataBind();
connection.Close();
}
}
Form
<form id="form1" runat="server">
<asp:ScriptManager ID = "ScriptManager" runat="server" />
<div>
<asp:Label runat="server" id = "orderByLabel" Text = "Order By: " />
<asp:DropDownList runat="server" ID="orderByList" AutoPostBack="true">
<asp:ListItem Value="fName" Selected="True">First Name</asp:ListItem>
<asp:ListItem Value="lName">Last Name</asp:ListItem>
<asp:ListItem Value="state">State</asp:ListItem>
<asp:ListItem Value="zip">Zip Code</asp:ListItem>
<asp:ListItem Value="cwaSource">Source</asp:ListItem>
<asp:ListItem Value="cwaJoined">Date Joined</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Label runat="server" ID="searchLabel" Text="Search For: " />
<asp:TextBox ID="searchTextBox" runat="server" Columns="30" />
<asp:Button ID="searchButton" runat="server" Text="Search" />
</div>
<div>
<asp:UpdatePanel ID = "up" runat="server">
<ContentTemplate>
<div style= "overflow:auto; height:50%; width:100%">
<asp:GridView ID="DefaultGrid" runat = "server" DataKeyNames = "IdentityColumn"
onselectedindexchanged = "DefaultGrid_SelectedIndexChanged"
autogenerateselectbutton = "true">
<SelectedRowStyle BackColor="Azure"
forecolor="Black"
font-bold="true" />
<Columns>
<asp:TemplateField HeaderText="Processed">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxProcess" AutoPostBack = "true" Checked ='<%#Eval("processed") %>' OnCheckedChanged="CheckBoxProcess_CheckedChanged" runat="server" Enabled="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
<div style= "overflow:auto; height:50%; width:100%" />
<table border="1">
<tr>
<td>Name: </td>
<td><%=name %></td>
</tr>
<tr>
<td>Zip: </td>
<td><%=zip %></td>
</tr>
<tr>
<td>Email: </td>
<td><%=email %></td>
</tr>
<tr>
<td>Length: </td>
<td><%=length %></td>
</tr>
<tr>
<td>Price: </td>
<td><%=price %></td>
</tr>
<tr>
<td>Source: </td>
<td><%=source %></td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
I have never used the UpdatePanel since my company uses Telerik, but from the examples I see during my research I remember seeing a trigger component.
From my understanding, if the control is w/i the UpdatePanel itself, then you do not have to specify the trigger, since it is assumed.
For your scenario, the trigger (dropdownlist) is outside of the UpdatePanel. You may need to include this in your aspx:
<asp:UpdatePanel ID = "up" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="orderByList" >
</Triggers>
<ContentTemplate>
...
Try the following:
In HTML move the update panel direct after the scriptmanager line.
Move the code lines in vieworders_PreInit to vieworders_PageLoad with !IsPostPack clause.

Asp.Net binding specific fields of sql query to Listview

I have a listview that has a few different controls. I need to bind specific fields of a query to certain parts of a control. The table contains a friendid and a firstname. I want to put the friendid at the end of a URL. I want to put the firstname in the text of a label. There will be multiple friends returned on the query. The listview should show all in a separate row. Here is what I have, which is obviously not right.
<asp:ListView ID="lvFriends" runat="server">
<LayoutTemplate>
<ul ID="itemPlaceholderContainer" runat="server" style="">
<li ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<div style="float:left;">
<a id="A1" href='<%# ResolveUrl(String.Format("~/UserPages/FriendsPages/FriendsProfile.aspx?friend={0}", Container.DataItem)) %>' runat="server"><asp:Image ID="ImageButton1" ImageUrl='<%# ResolveUrl(String.Format("~/UserPages/FriendsPages/FriendsThumbImage.aspx?friend={0}", Container.DataItem)) %>' runat="server" /></a>
</div>
<div style="margin-left:300px;">
<ul>
<li><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FriendFN") %>' /></li>
</ul>
</div>
</li>
<div style="clear:both;"></div>
</ItemTemplate>
<ItemSeparatorTemplate><br /></ItemSeparatorTemplate>
</asp:ListView>
CODE BEHIND:
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT * from [Friends] WHERE [UserId] = #UserId";
cmd.Parameters.AddWithValue("#UserId", User.Identity.Name);
DataTable dtFriends = new DataTable();
dtFriends.Columns.Add("FriendId");
dtFriends.Columns.Add("FriendFN");
SqlDataReader nwReader = cmd.ExecuteReader();
while (nwReader.Read())
{
string RdFriendId = nwReader["FriendId"].ToString().ToLower();
string RdFriendFN = nwReader["FriendFirstName"].ToString().ToLower();
dtFriends.Rows.Add(new object[] {RdFriendId, RdFriendFN});
}
nwReader.Close();
Session.Add("FriendsTable", dtFriends);
conn.Close();
lvFriends.DataSource = dtFriends;
lvFriends.DataBind();
}
}
I would look into using a repeater control instead.

Resources