The looping only shows one data - c#

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();

Related

How to add data from textbox to database table

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)

Cannot access control inside DetailsView Edit template

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
}
}
}

Store ID from a dropdown list

I have been working on this for a while but seems I can't figure this out. So I have a dropdown list called ddStudent where the textField value is from a sql table I made called 'Student from a column called 'firstName'. Now I used the 'studentID' as the value field.
Here is where I am having the issue. I want to execute my stored procedure that takes studentID as a paramter but I don't understand how to store the actual student ID into the parameter.
Here is what I have so far-
protected void btnRegister_Click(object sender, EventArgs e)
{
int selValClass = Convert.ToInt32(ddClassNames.SelectedValue);
int selValStudent = Convert.ToInt32(ddStudents.SelectedValue);
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("procRegStudent", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#studentID", selValStudent);
cmd.Parameters.AddWithValue("#classID", selValClass);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
and here is my code for databinding-
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT studentID, firstName, lastName, ssn, address, city, state, zip FROM Student ", con);
con.Open();
ddStudents.DataSource = cmd.ExecuteReader();
ddStudents.DataTextField = "firstName";
ddStudents.DataValueField = "studentID";
ddStudents.DataBind();
}
Now my question is, is there a way I can store the actual studentID from the dropdown list when I select it? For some reason when I do this, the page reloads and selects the first student ID for a student I didn't select. I'm not exactly sure what's going on.
Thanks.
EDIT-
I wanted to make sure I clarify-
I have 3 students in my student dropdown. When I select student 3 (with student ID 3), the first student in the dropdownlist is being passed as the parameter and I can't tell why.
This issue is logical for Dropdownlist control because your dropdownlist missed to have a defaultitem to render when it comes back from the server.The soultion is very simple you should add a default list item to be the default value when the page loads
Here I made a simple example to how can we solve this issue :
in the Page.aspx:
<asp:DropDownList ID="ddStudents" runat="server" DataTextField = "firstName" DataValueField = "studentID" AppendDataBoundItems="true">
<asp:ListItem Text="===Select Student===" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnRegister" runat="server" Text="Register" OnClick="btnRegister_Click" />
<asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
in the Page.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDown();
}
}
private void BindDropDown()
{
DataTable dt = new DataTable();
dt.Columns.Add("studentID", typeof(int));
dt.Columns.Add("firstName", typeof(string));
dt.Rows.Add(dt.NewRow());
dt.Rows[0]["studentID"] = 1;
dt.Rows[0]["firstName"] = "Markus";
dt.Rows.Add(dt.NewRow());
dt.Rows[1]["studentID"] = 2;
dt.Rows[1]["firstName"] = "Arthur";
ddStudents.DataSource = dt;
ddStudents.DataBind();
}
protected void btnRegister_Click(object sender, EventArgs e)
{
if (ddStudents.SelectedIndex > 0)
{
lblMessage.Text = String.Format("You selected {0} with Number : {1}", ddStudents.SelectedItem.Text,ddStudents.SelectedValue);
}
}
Hint: I marked the dropdownlist AppendDataBoundItems Property to true just to tell the dropdownlist to include the default listitem when the data binded..
I hope my code helps you solving your problem :)
Try with this
int selValStudent = int.Parse(this.ddStudents.SelectedValue);
and put your
BindDropDown();
into your postback

Bind data using Repeater in c# ASP.NET

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.

.NET web form drop down list resets on postback

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();
}

Categories