I need to bind some data on view page and the data will fetch from database using c# asp.net.I tried to implement Repeater but i can not know how to bind multiple data inside it.the following is my original view file.
index.aspx:
<div class="wpb_wrapper text-justify">
<asp:Repeater runat="server" ID="rptMissionId" >
<ItemTemplate>
<img src="pic/our-phylosophy.jpg" width="260" height="246" alt="" class="alignleft">
<h1>
<b>Heading</b>
</h1>
<p>
description
</p>
<br/>
<h1>
<b>Heading</b>
</h1>
<p>
description
</p><br>
</ItemTemplate>
</asp:Repeater>
</div>
In the above section one image is present and two set of data also there.Here i need to fetch image from database and set here in image place similarly heading and description in their proper place.My requirement is the last row of table image will set here and the heading,description of last two row will set here.
I am using 3-tire architecture here so please check my below code.
index.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
indexBL objMissionBl = new indexBL();
rptMissionId.DataSource = objMissionBl.getMissionData();
rptMissionId.DataBind();
}
indexBL.cs:
private indexDL objMissionDL = new indexDL();
public DataSet getMissionData()
{
try
{
DataSet ds = objMissionDL.getMissionData();
return ds;
}
catch (Exception e)
{
throw e;
}
}
IndexDL.cs:
SqlConnection con = new SqlConnection(CmVar.convar);
public DataSet getMissionData()
{
con.Open();
try
{
DataSet ds = new DataSet();
string sql = "SELECT TOP 1 * FROM T_Mission_Vission WHERE Heading='Mission' ORDER BY Mission_vision_ID DESC";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(ds);
con.Close();
return ds;
}
catch (Exception e)
{
throw e;
}
}
I explained my requirement,if something is wrong or need to add please change it and help me to resolve this.Thanks.
Related
I am a student and just start learning asp.net with C#.
I am using visual Studio 2015 and MSSQL Server 2012. I am facing a problem adding data in the database table from a webform.
I have established the connection successfully but couldn't be able to insert the data in the database table from a textbox.
I have search it at many places but couldn't able to do that.
So can anybody please tell me the simple and exact method to do that?
Kumar I am not sure if you facing issue in inserting any data into database or in capturing text from textbox and then inserting it into database.
However i will try to address both the issue.
for inserting into database you can visit Invalid column name sql error
as it has already been answered
now to capture the text froim textbox you can make use of HtmlElementClass
HtmlElement txtBox = null;
HtmlDocument doc = webBrowser1.Document;
if (doc != null)
{
txtBox = doc.GetElementByID("TxtboxelementId");
string txtValue=txtBox.InnerHtml
}
ASPX Page :
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtValue" runat="server"></asp:TextBox>
<asp:Button ID="btnInsert" runat="server" Text="Button" OnClick="btnInsert_Click" />
</div>
</form>
CS Code :
protected void Page_Load(object sender, EventArgs e)
{
}
private void InsertValue(string value)
{
using (SqlConnection con = new SqlConnection("YOUR_CONNECTION_STRING")) //Creating connection object
{
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO YOUR_TABLE_NAME (Field_Name) VALUES (#value)", con))
{
if (con.State == System.Data.ConnectionState.Closed) con.Open();
cmd.Parameters.AddWithValue("#value", value); // Adding parameter with value to command object
int result = cmd.ExecuteNonQuery(); // Executing query and it returns no of rows affected.
if (result > 0) Response.Write("Successful."); // Checking if no of rows affected is > 0 meaning value successfully inserted.
}
}
catch (SqlException ex) //Handling SQL Exceptions
{
this.LogErrors(ex);
}
}
}
private void LogErrors(Exception ex)
{
// Write error log logic here
}
protected void btnInsert_Click(object sender, EventArgs e) // insert data button click event handler
{
this.InsertValue(this.txtValue.Text);
}
SqlConnection con= (Connection Name)
If you are using without primary key in Database please go ahead with this
SqlCommand query = new SqlCommand("Insert into TABLE values ("+txtsample1.Text+")",con)
If it's with primary key mention your field names
SqlCommand query = new SqlCommand("Insert into TABLE (column1) values ("+txtsample1.Text+")",con)
I am new to C# and currently studying myself. In my project what I would like to do is to take 10 data from a table and to be show in a loop. For example if it has 10 data, so all the data will be shown in the default.aspx page. Currently my code can only display the first row and loop it 10 time. Below is my sample.
namespace CRM_Attachment
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Sample"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com;
con.Open();
string str = "SELECT TOP 10 FILE_NAME FROM FILE";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
//if (reader.HasRows)
//{
while (reader.Read())
{
labelname1.Text = reader["FILE_NAME"].ToString();
}
//}
reader.Close();
con.Close();
}
}
}
Below is my default.aspx page..
<body>
<form id="form1" runat="server">
<% for (int i=0;i<10;i++) {%>
<div>
<asp:Label ID="labelname1" runat="server" Text="Label"></asp:Label>
</div>
<%}%>
</form>
May I know what I am doing wrong. Thank you in advance.
You are setting the "Text" property of same label 10 times. It is being overwritten on every iteration of the loop. You should append the value of column from database to label. Modify code as below:
labelname1.Text += reader["FILE_NAME"].ToString();
Hello everybody and thanks in advance,
Well, I have a DetailsView in my .aspx file and I can't access to a CheckBoxList control placed in the DetailsView's edit template. I've read a lot of threads about this but still can't find a solution. Here's the code...
<asp:DetailsView ID="MyDetailsView" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataSourceID="DataMyDetailsView">
...
...
<asp:TemplateField HeaderText="DATA" SortExpression="DATA">
<EditItemTemplate>
<div style="width:400px; height:300px; overflow-y:auto">
<asp:CheckBoxList ID="DataCL" runat="server" DataSourceID="DataEDIT" DataTextField="DATA" DataValueField="ID_DATA">
</asp:CheckBoxList>
</div>
Then, in my .cs file I have this piece of code...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Do something
}
else
{
CheckItems();
}
}
...
...
public void CheckItems()
{
CheckBoxList DataCL = (CheckBoxList)MyDetailsView.FindControl("DataCL");
using (conexion)
{
conexion.Open();
cmd.Connection = conexion;
DataSet ds = new DataSet();
string cmdstr = "SELECT * FROM DATA";
SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conexion);
adp.Fill(ds);
DataCL.DataSource = ds;
DataCL.DataTextField = "DATA";
DataCL.DataValueField = "ID_DATA";
DataCL.DataBind();
The problem is that when the execution reaches the first line in which the control is called (DataCL.DataSource = ds;), a "NullPointerExeception" is thrown, however I can access easily to controls in ItemTemplate.
Please, can someone help me in this. Thanks again!
You can't do this, because this control is dynamically created after data binding. Instead attach your grid to DataBound (MSDN) event and bind checked box list there
protected void MyDetailsView_DataBound(object sender, EventArgs e)
{
if (MyDetailsView.CurrentMode == DetailsViewMode.Edit)
{
CheckBoxList DataCL = (CheckBoxList)MyDetailsView.FindControl("DataCL");
using (conexion)
{
// your data bound code goes here
}
}
}
I've searched through a heap of similar questions and done a bit of googling but I cannot find the answer to my problem...
I would like to have a drop down list that is populated by categories in a database...upon selecting a category and hitting submit, a gridview is populated with all the items in that category.
Now, everything works, except whenever I select anything in the category drop down box, it resets straight away to the first selection. So I'm unable to submit any value other than the first to the gridview. I am using autopostback on this item. I have tried to use appenddatabounditems too but that just populated the list with more and more of the same entries...
I would love if anyone could tell me how I can just get the dropdownlist to hold its position after postback?
Selected Category:
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True" ViewStateMode="Enabled">
</asp:DropDownList>
<asp:Button ID="buttonCategorySubmit" runat="server" OnClick="buttonCategorySubmit_Click" Text="Submit" />
<br />
</div>
<asp:GridView ID="CategoryGridView" runat="server">
</asp:GridView>
<br />
protected void Page_Load(object sender, EventArgs e)
{
PopulateCategorySelection();
}
public void PopulateCategorySelection()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]);
SqlCommand cmd = new SqlCommand("AllCategories", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader ddlValues = cmd.ExecuteReader();
ddlCategory.DataSource = ddlValues;
ddlCategory.DataValueField = "CategoryID";
ddlCategory.DataTextField = "Title";
ddlCategory.DataBind();
conn.Close();
}
protected void buttonCategorySubmit_Click(object sender, EventArgs e)
{
PopulateCategoryTable();
}
public void PopulateCategoryTable()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["Connstring"]);
SqlCommand cmd = new SqlCommand("SelectCategory", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Selected", ddlCategory.SelectedItem.Value);
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
conn.Close();
CategoryGridView.DataSource = ds.Tables[0];
CategoryGridView.DataBind();
conn.Close();
}
I literally just worked it out everyone...For anyone that has the same issue, you need to check in the page_load method whether the page is loading because a new page is being generated, or information is just being posted-back for the user. If its just postback, we dont want to populate the category dropdown box again. So we use the IsPostBack object in the page_load method, like this:
if (!IsPostBack)
{
PopulateCategorySelection();
}
I am using a DataTable to populate a dropdownlist on my web form, as well as using a stored procedure to query the database. The list retrieves only one field from the database and will be used in conjunction with a gridview to view all reservations made on a specific date.
Everything works fine, except for the format of the date. Right now it is showing the date as well as hours, minutes, and seconds. I have tried using the DataFormatString property the the web form but no luck.
Webform:
<b>Please select a date:</b>
<asp:DropDownList ID="ddlDateSelection" runat="server" DataFormatString="{0:MM/dd/yyyy}"></asp:DropDownList>
<br />
<asp:Label ID="lblError" runat="server" CssClass="validate"></asp:Label>
code behind used to query database:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
loadDates();
}
protected void loadDates()
{
DataTable dates = new DataTable();
using (SqlConnection con = new SqlConnection(DBAccess.GetConnectionString()))
{
SqlCommand cmd = new SqlCommand("usp_sel_ReservationDates", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dates);
ddlDateSelection.DataSource = dates;
ddlDateSelection.DataTextField = "ReservationDate";
ddlDateSelection.DataBind();
}
catch (Exception ex)
{
lblError.Text = "Something bad has happened. Please try again.<br />Message: " + ex;
}
}
ddlDateSelection.Items.Insert(0, new ListItem("Please Select", "0"));
}
Any help would be greatly appreciated, as this is a learning project for myself. Thanks
Probably you need to refer to the correct property
<asp:DropDownList ID="ddlDateSelection" runat="server"
DataTextFormatString="{0:MM/dd/yyyy}">
</asp:DropDownList>
DropDownList properties
You can edit your SQL code to return only date
SELECT CONVERT (DATE, GETDATE())
RESULT: 2013-07-14