I am new to ASP.NET, I am making a search box in my application.
For example: if a user enters "abc" in the textbox, then the textbox will fetch data from the database which starts with "abc". I am passing this data to DataTable.
It works properly,
Here is my code snippet:
DataTable result = new DataTable();`
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string query = string.Format("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '{0}%'", TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
result.Load(cmd.ExecuteReader());
conn.Close();
}
Now I want to retrieve all this data in my <div> tag. How should I retrieve and display?
Any help will be appreciated.
You should use a databound control like a ListView or GridView. I'd recommend creating a separate control to hold one row in the list and using the RowDataBound method to assign the row data. Example of using ListView's ItemDatabound event - http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound.aspx
On a side note your code is vulnerable to SQL Injection
You could probably better use a databound control, like the ListView (or the GridView) control. This way you can create nice layouts you want with the data in the datatable.
For instance, a ListView could be used:
<asp:ListView ID="lvwItems" runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("ColumnFromDataTable")%>
</div>
</ItemTemplate>
</asp:ListView>
In your code behind you can then do:
lvwItems.DataSource = result;
lvwItems.DataBind();
Remark: code is just out of my head, could contain some errors
Related
Currently i have two problems.
Problem 1. Im trying to change the Visibility of two Panels based on what value the reader gets from reader["Maskine_Type"].ToString() as you can see in the Codebehind below. Because the Panels are inside a repeater i also use the:
Panel PanelTilbud = (Panel)Page.FindControl("PanelTilbud"); again you can see below. however, when i run the code it gives me a Object reference not set to an instance of an object on PanelTilbud.Visible = true; i assume because it still cant find the Panels. i tested with panels outside of the repeater and it works fine.
I also tried to make the Repeater OnItemDataBound="Repeater1_ItemDataBound"
and changed to Panel PanelTilbud = (Panel)e.Item.FindControl("PanelTilbud");
However then i get the error Insufficient stack to continue executing the program safely
Problem 2.
Inside one of the panels, i run this code
<%# (Eval("Maskine_Tilbud").ToString().Substring(Eval("Maskine_Tilbud").ToString().Length - 2))%>
in order to remove the first two characters in the string from Eval("Maskine_Tilbud") which works fine, however most records in the database will have a null inMaskine_Tilbud and if its null i get the error StartIndex cannot be less than zero which makes sense, but i dont know how else to remove the first two characters from Eval("Maskine_Tilbud")
.aspx markup
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Panel ID="PanelTilbud" runat="server" Visible="false">
<hr />
<h4 class="radfont text-center">Tilbud! -<%# (Eval("Maskine_Tilbud").ToString().Substring(Eval("Maskine_Tilbud").ToString().Length - 2))%>% pr dag!</h4>
</asp:Panel>
<asp:Panel ID="PanelNormal" runat="server">
<hr />
<h4 class="text-center orangeFont"><%#Eval("Maskine_pris") %><span class="hvidfont">,- pr dag inkl moms</span>
<span class="orangeFont">(<%#Eval("Maskine_Upris") %>,- ekskl)</span>
</h4>
<hr />
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
My Codebehind - in Page_Load
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT top 1 * FROM [Maskiner] INNER JOIN Maskine_kategori ON Maskiner.Maskine_Kategorinavn = Maskine_kategori.Maskine_kategori_id WHERE ([Maskine_id] = #Maskine_id)";
cmd.Parameters.Add("#Maskine_id", SqlDbType.Int).Value = Request.QueryString["Maskine_id"];
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
Panel PanelTilbud = (Panel)Page.FindControl("PanelTilbud");
Panel PanelNormal = (Panel)Page.FindControl("PanelNormal");
if (reader.Read())
{
if (reader["Maskine_Type"].ToString() == "Tilbud")
{
PanelTilbud.Visible = true;
PanelNormal.Visible = false;
}
if (reader["Maskine_Type"].ToString() == "Normal")
{
PanelTilbud.Visible = false;
PanelNormal.Visible = true;
}
}
conn.Close();
DataTable select_favorit_db = new DataTable();
SqlDataAdapter dt = new SqlDataAdapter(cmd);
dt.Fill(select_favorit_db);
Repeater1.DataSource = select_favorit_db;
Repeater1.DataBind();
I hope you can understand my questions.
Late to the party here. Just thought I should add that you can have methods in your page and use them in your data binding expressions. Sample:
ASPX:
<form id="form1" runat="server">
<asp:Repeater ID="rep" runat="server">
<ItemTemplate>
<asp:Label ID="lab" runat="server"
Text='<%# Trim2Chars(Eval("test")) %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
//create fake data for demo and bind to repeater
var data = Enumerable.Range(0, 10).Select(i => new { test = "foo " + i });
rep.DataSource = data;
rep.DataBind();
}
public string Trim2Chars(object input)
{
string inputString = input as string;
if (inputString == null)
return "";
if (inputString.Length < 2)
return inputString;
return inputString.Substring(2);
}
This way, you can keep the ASPX file a bit cleaner and have more complex data binding expressions evaluated in the code behind.
You can set the Visibility in the Control itself
<asp:Panel ID="PanelTilbud" runat="server" Visible='<%# Eval("Maskine_Type").ToString() == "myValue" %>'>
</asp:Panel>
Or in the ItemDataBound event code behind
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//use findcontrol to find the panel and cast it as one
Panel panel = e.Item.FindControl("PanelTilbud") as Panel;
//get the current datarowview
DataRowView row = e.Item.DataItem as DataRowView;
//check the value and change the panel visibility
if (row["Maskine_Type"].ToString() == "myValue")
{
panel.Visible = true;
}
}
To check for NULL values you have to use a ternary operator.
<%# !string.IsNullOrEmpty(Eval("Maskine_Type").ToString()) ? Eval("Maskine_Type").ToString().Substring(0, Eval("Maskine_Type").ToString().Length - 2) : "Field is empty" %>
I currently have a parent repeater and two child repeaters on my page. I am wanting to dynamically pull data from our database and display them within the repeaters. I followed the Microsoft guide and a few SO questions on how to do this, and this is what I have arrived at:
<!-- start parent repeater -->
<asp:repeater id="parentRepeater" runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem,"EquipmentTypeName") %>"><%# DataBinder.Eval(Container.DataItem,"EquipmentTypeName") %><label><input type="checkbox"></label></div><ul runat="server">
<!-- start child repeater1 -->
<asp:repeater id="Repeater1" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem, "[\"MakeID\"]")%>"><%# DataBinder.Eval(Container.DataItem, "[\"MakeID\"]")%><label><input type="checkbox"></label></div><ul runat="server">
<!-- start child repeater2 -->
<asp:repeater id="childRepeater2" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation2") %>' runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem, "[\"YearID\"]")%>"><%# DataBinder.Eval(Container.DataItem, "[\"YearID\"]")%><label><input type="checkbox"></label></div><ul runat="server">
</ul></li></itemtemplate>
</asp:repeater>
<!-- end child repeater2 -->
</ul></li></itemtemplate>
</asp:repeater>
<!-- end child repeater1 -->
</ul></li></itemtemplate>
</asp:repeater>
<!-- end parent repeater -->
And the code behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
//Create the connection and DataAdapter for the Authors table.
string Connection = WebConfigurationManager.ConnectionStrings["md_dbConnectionString"].ConnectionString;
SqlConnection cnn = new SqlConnection(Connection);
SqlDataAdapter cmd1 = new SqlDataAdapter("select * from EquipmentType", cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "EquipmentType");
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from Make", cnn);
cmd2.Fill(ds, "Make");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd3 = new SqlDataAdapter("select distinct MakeID, TypeID, YearID from Parts", cnn);
cmd3.Fill(ds, "Parts");
//Create the relation bewtween the Authors and Titles tables.
ds.Relations.Add("myrelation",
ds.Tables["EquipmentType"].Columns["EquipmentTypeID"],
ds.Tables["Parts"].Columns["TypeID"]);
ds.Relations.Add("myrelation2",
ds.Tables["Make"].Columns["MakeID"],
ds.Tables["Parts"].Columns["MakeID"]);
//Bind the Authors table to the parent Repeater control, and call DataBind.
parentRepeater.DataSource = ds;
Page.DataBind();
//Close the connection.
cnn.Close();
}
If I load the page with only one child repeater, everything works fine, I get the correct data displaying, but when I add the second child repeater in, I get the following error message: Unable to cast object of type 'System.Data.DataRow' to type 'System.Data.DataRowView'. This fires on thedatasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation2") %>'` ASP line.
The tables that I am trying to pull from are structured this way:
EquipmentType
EquipmentTypeID | EquipmentTypeName
Make
MakeID | MakeName
Year
YearID
Parts
PartID | MakeID | YearID | TypeID
Each table references the Parts table.
More or less what I want the repeater to do is display all of the EquipmentTypes, then only display the make is we have a part for it in the database. Once the make is selected, then only display the year that we have parts for that make and equipmenttype in the database.
Did you try to cast it to DataRow:
<%# ((DataRow)Container.DataItem).GetChildRows("myrelation2") %>
For anyone else experiencing this issue. It could be that there is a missing tag at the top of the page. <%# Import Namespace="System.Data" %>
I have multiple images which i want to display. the image count varies on input. I am able to see the broken images on the screen. In console the ERR_INVALID_URL is displayed. Please let me know where i am wrong.
Below is my aspx code
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Image ID="Image3" runat="server"
ImageUrl="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />
</ItemTemplate>
</asp:Repeater>
cs code
foreach (DataRow row in dt.Rows)
{
Byte[] bytes = (Byte[])row["image"];
viewDataList.Add(new view_data { image = Convert.ToBase64String(bytes)});
}
Repeater1.DataSource = viewDataList;
Repeater1.DataBind();
I am fetching the images from database.Is this the correct way to do this.. Kindly suggest
Update..
I have changed the image tag to the below. Now there are 4 images that need to be displayed out of which i am able to see 1 image and the rest 3 are broken.. Kindly suggest
<img src="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />
Try in this way with your requirements. Let me know, if you have any issues once you completed with below methods.
Note: I tried with separate column name as Image ID.If you have it in your database it will be of more useful to proceed this. Otherwise, you pass the Image directly to the repeater and pass the same to the ImageHandler.ashx
HTML Page:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Image ID="Image3" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' Height="150px" Width="150px"/>
</ItemTemplate>
CS Code:
On your click event:
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]",connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
ImageHandler.ashx
After Completion of above code we need to add HTTPHandler file to our project to retrieve images from database because we save our images in binary format getting the binary format of data from database it’s easy but displaying is very difficult that’s why we will use HTTPHandler to solve this problem.
Here HTTPHandler is a simple class that allows you to process a request and return a response to the browser. Simply we can say that a Handler is responsible for fulfilling requests from the browser. It can handle only one request at a time, which in turn gives high performance.
Right Click on your project add new HTTPHandler.ashx file and give name as ImageHandler.ashx and write the following code in pagerequest method like this
string strcon =ConfigurationManager.AppSettings["ConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Image from Image where ImageID="+ imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
Here don’t forgot to set the connection string in web.config file here I am getting database connection from web.config file for that reason you need to set the connectionstring in web.config file like this
<connectionStrings>
<add name="dbconnection" connectionString="DataSource=Yourservername;Integrated Security=true;InitialCatalog=Your databasename"/>
</connectionStrings>
Source: Retrieve Image from database
Changing the image tag to the below worked for me..
<img src="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />
Thanks for your response
There is no need to foreach to bind data in repeater you can directly specify DataTable to Your repeater control
DataTable dt=new DataTable();
dt=cmd.ExecuteNonQuery();
Repeater1.DataSource = dt;
Repeater1.DataBind();
you can place this line
<asp:Image ID="Image3" runat="server"
ImageUrl='<%#Bind("image")%>' />
instead of
<asp:Image ID="Image3" runat="server"
ImageUrl="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />
I ask this question because I think I have different problem with this : How to hide gridview column after databind?
My gridview has data from database. I don't set any "td" in my code, but html changes the gridview to table and have "td". The problem is, I don't want the cell or "td" is shown on the page, I just want to receive the data in the cell to show the image in the database.
This is code to retrieve data from database:
public static DataTable FetchAllImagesInfo(int id)
{
string sb = "Select img_content, Img_id, csrid FROM images WHERE Img_Id = " + id + ";";
SqlConnection conn = DatabaseFactory.GetConnection();
SqlDataAdapter da = new SqlDataAdapter(sb, conn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
This is codebehind to bind GridView, here I tried to set Visible to true or false, but it doesn't work. I set column index manually because it's only has 3 column :
GridView1.DataSource = ProductAllLocationCatalog.FetchAllImagesInfo(_id);
GridView1.DataBind();
GridView1.Columns[0].Visible = true;
GridView1.Columns[1].Visible = false;
GridView1.Columns[2].Visible = false;
And, this is my aspx code :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField runat="server">
<ItemTemplate runat="server">
<asp:Image ID="image1" runat="server" ImageUrl='<%#"Handler.ashx?csrid="+Eval("csrid") %>' style="max-height:400px; max-width:940px; text-align:center; margin:auto; display:block;" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I just need the image from the database, not other. But if I only SELECT the image, gridview can not do DataBind(), and I can't get value of "csrid".
Thank you!
Try
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[1].Visible = false;
e.Row.Cells[2].Visible = false;
}
I believe the issue is that your GridView is automatically generating your columns, and the GridView.Columns property only stores explicitly declared columns. Instead of hiding the column, you can hide the cells comprising the columns you don't want when each row is bound. It seems like there should be a better way to handle this, but outside of using explicitly declared columns, I don't know one.
I am making a project in ASP.NET WebForms. Although I have done it so many times but dropdown list is troubling me a lot this time.
I fetch items from DB and then add them to my dropdown list one by one using FOR loop. That works fine. But the problem is that I cannot select an item from list comfortably, whenever I try to select an item from the drop down list, it snaps the selection to the first element, it becomes very difficult to select the desired item.
How could I fix that?
Suppose I move my cursor over the 9th item in the list then also it selects the 1st and 9th item alternatively so fast that I see both of them as selected.
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.Items.Clear();
con.ConnectionString = ConfigurationManager.ConnectionStrings["familyConnectionString"].ConnectionString;
con.Open();
adp = new SqlDataAdapter("select distinct family_head from family", con);
DataSet ds = new DataSet();
adp.Fill(ds, "family");
con.Close();
for (int i = 0; i < ds.Tables["family"].Rows.Count; i++)
DropDownList1.Items.Add(ds.Tables["family"].Rows[i][0].ToString());
}
}
ASPX
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:DropDownList ID="DropDownList1" runat="server" Width="150px">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" Width="150px">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Height="30px" onclick="Button1_Click"
Text="Submit" Width="145px" BackColor="#465767" ForeColor="White" />
<asp:RoundedCornersExtender ID="Button1_RoundedCornersExtender" runat="server"
Enabled="True" TargetControlID="Button1" Corners="All" Radius="10">
</asp:RoundedCornersExtender>
<br />
<br />
<br />
</asp:Content>
A CSS Keyframes Animation is working in page background, Can that be a cause?
There seems to be some kind of confusion, as to how databinding works for WebControls. The best reference for that is: http://msdn.microsoft.com/en-us/library/ms178472.aspx
Under the assumption, that all the binding code for DropDownList1 is shown:
DropDownList1.Items.Clear();
shouldn't be neccesary, as the items shouldn't persist per PostBack. (At least I assume that, because all Items will be lost after each PostBack if the DataSource isn't bound again).
The DropDownList needs have the items on each PostBack, if you want to use the DropDownList. You are using
if (!Page.IsPostBack)
which means, that you don't bind the items again, if you have a PostBack. In the link posted above, you can see that Controls set their properties (like which item was selected before clicking a Button) during the LoadEvent, which means that the items need to be binded earlier in the lifecycle, like during OnInit.
Try something like this:
protected void BindDropDownList1()
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["familyConnectionString"].ConnectionString;
con.Open();
adp = new SqlDataAdapter("select distinct family_head from family", con);
DataSet ds = new DataSet();
adp.Fill(ds, "family");
con.Close();
for (int i = 0; i < ds.Tables["family"].Rows.Count; i++)
DropDownList1.Items.Add(ds.Tables["family"].Rows[i][0].ToString());
}
protected override void OnInit(EventArgs e)
{
this.BindDropDownList1();
base.OnInit(e);
}
Another suggestion would be to you the DataSource property of the DropDownList, instead of DropDownList1.Items.Add. If you use this approach, you need to set the DataKeyValue and DataKeyMember properties of the DropDownList:
protected void BindDropDownList1()
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["familyConnectionString"].ConnectionString;
con.Open();
adp = new SqlDataAdapter("select distinct family_head from family", con);
DataSet ds = new DataSet();
adp.Fill(ds, "family");
con.Close();
DropDownList1.DataSource = ds;
DropDownList1.DataBind();
}
Edit:
I think I found your error. You are using controls from the AjaxControlToolKit, but are still using the ScriptManager. For about 2 years, controls from the AjaxControlToolKit require the ToolkitScriptManager. Replace the ScriptManager with a ToolkitScriptManager.