Repeated in ASP.NET - asp.net

The following code displays only the last record from the database. How to display all records?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Collections;
using System.Data.Odbc;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=softmail;" + "UID=root;" + "PASSWORD=********;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("Select name, email, website, comments from awm_comments", MyConnection);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
while (dr.Read())
{
if (!IsPostBack)
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
ArrayList values = new ArrayList();
values.Add(new PositionData(a, b, c, d));
Repeater1.DataSource = values;
Repeater1.DataBind();
Repeater2.DataSource = values;
Repeater2.DataBind();
}
}
}
public class PositionData
{
private string name;
private string ticker;
private string val3;
private string val4;
public PositionData(string name, string ticker, string val3, string val4)
{
this.name = name;
this.ticker = ticker;
this.val3 = val3;
this.val4 = val4;
}
public string Name
{
get
{
return name;
}
}
public string Ticker
{
get
{
return ticker;
}
}
public string Val3
{
get
{
return val3;
}
}
public string Val4
{
get
{
return val4;
}
}
}
}

At the moment you are creating a new ArrayList for each record; then, you're binding that new list to the repeater and overwriting the previous binding.
Instead, you need to add all your values to your list and only bind it once you've read all of your data - move your variable declaration before your loop and your DataBind invocation after your loop, like so:
ArrayList values = new ArrayList();
while (dr.Read())
{
if (!IsPostBack)
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
values.Add(new PositionData(a, b, c, d));
}
}
Repeater1.DataSource = values;
Repeater1.DataBind();
Repeater2.DataSource = values;
Repeater2.DataBind();

You are constantly resetting the values for that repeater.
What you should do is first collect all records into a single ArrayList and only when that is done execute a single DataBind();
Something like:
if (!IsPostBack)
{
ArrayList values = new ArrayList();
while (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
string d = dr[3].ToString();
values.Add(new PositionData(a, b, c, d));
}
Repeater1.DataSource = values;
Repeater1.DataBind();
Repeater2.DataSource = values;
Repeater2.DataBind();
}

Related

"Cannot implicitly convert type 'Lab06.Attendance' to 'System.Collections.Generic.List<Lab06.Attendance>" How to solve this error

AssignmentAttendance.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services.Description;
namespace Lab06 {
public partial class AssignmentAttendance : System.Web.UI.Page
{
Attendance aAttendance = new Attendance();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
protected void bind()
{
List<Attendance> attendancelist = new List<Attendance>();
attendancelist = aAttendance.getAttendanceAll();
GridView1.DataSource = attendancelist;
GridView1.DataBind();
}
protected void Retrieve_Attendance_Click(object sender, EventArgs e)
{
string attributename = tb_classcode.ToString();
List<Attendance> attendanceList = new List<Attendance>();
attendanceList = aAttendance.getAttendance(attributename);
GridView1.DataSource = attendanceList;
GridView1.DataBind();
}
/* protected void edit_attendance(object sender, GridViewEditEventArgs e)
{
}*/
}
}
AssignmentContentUploadClass.cs
public class Attendance {
string _connStr =ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString;
private string _ClassCode = null;
private string _Teacher_ID = "";
private string _TeachingSessions = "";
private string _Remarks = "";
public Attendance()
{
}
// Constructor that take in all data required to build a Product object
public Attendance(string ClassCode, string Teacher_ID, string TeachingSessions, string Remarks)
{
_ClassCode = ClassCode;
_Teacher_ID = Teacher_ID;
_TeachingSessions = TeachingSessions;
_Remarks = Remarks;
}
public string ClassCode
{
get { return _ClassCode; }
set { _ClassCode = value; }
}
public string Teacher_ID
{
get { return _Teacher_ID; }
set { _Teacher_ID = value; }
}
public string TeachingSessions
{
get { return _TeachingSessions; }
set { _TeachingSessions = value; }
}
public string Remarks
{
get { return _Remarks; }
set { _Remarks = value; }
}
public int createAttendance()
{
int result = 0;
string queryStr = "INSERT INTO Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks)"
+ " values (#ClassCode, #Teacher_ID, #TeachingSessions, #Remarks)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#ClassCode", this.ClassCode);
cmd.Parameters.AddWithValue("#Teacher_ID", this.Teacher_ID);
cmd.Parameters.AddWithValue("#TeachingSessions", this.TeachingSessions);
cmd.Parameters.AddWithValue("#Remarks", this.Remarks);
conn.Open();
result += cmd.ExecuteNonQuery(); // Returns no. of rows affected. Must be > 0
conn.Close();
return result;
}//end Insert
public Attendance getAttendance(string ClassCode)
{
Attendance attendanceDetail = null;
string Teacher_ID, TeachingSessions, Remarks;
string queryStr = "Select * From Attendance Where ClassCode = #ClassCode";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#ClassCode", ClassCode);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Teacher_ID = dr["Teacher_ID"].ToString();
TeachingSessions = dr["TeachingSessions"].ToString();
Remarks = dr["Remarks"].ToString();
attendanceDetail = new Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks);
}
else
{
attendanceDetail = null;
}
conn.Close();
dr.Close();
dr.Dispose();
return attendanceDetail;
}
public List<Attendance> getAttendanceAll()
{
List<Attendance> attendancelist = new List<Attendance>();
string ClassCode, Teacher_ID, TeachingSessions, Remarks;
string queryStr = "SELECT * FROM Attendance Order By ClassCode";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
ClassCode = dr["ClassCode"].ToString();
Teacher_ID = dr["Teacher_ID"].ToString();
TeachingSessions = dr["TeachingSessions"].ToString();
Remarks = dr["Remarks"].ToString();
Attendance a = new Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks);
attendancelist.Add(a);
}
conn.Close();
dr.Close();
dr.Dispose();
return attendancelist;
}
}
I am not sure of the error and thus I am not able to provide much
I am trying use the getAttendance(ClassCode) function to retrieve the data based off my input of my classcode in the textbox of my AssignmentAttendance.aspx.
I am thinking of using the getAttendance function in my AssignmentAttendance.aspx file by passing in the data of my classcode entry from the textbox to retrieve the details of the Attendance based off classcode.
However, I am not too sure how that works and might need some help
My database has:
ClassCode
Teacher_ID
TeachingSessions
Remarks
If anything is missing or I did not make things clear do let me know
-Edit-
I am getting an error from my AssignmentAttendance.aspx.cs file
attendanceList = aAttendance.getAttendance(attributename);

mail merge with dynamic file path

I had a problem generating a word template because I wanted it to be selected dynamically with ddlTemplate when selected to write in it with the merge field in the word template.
this is my code:
public partial class unTemplate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)// call the method for ONLY first time for visitor
{
{
populateDdlInstitution();
}
}
}
protected void populateDdlInstitution()
{
CRUD myCrud = new CRUD();
string mySql = #"select institutionid, institution from institution";
SqlDataReader dr = myCrud.getDrPassSql(mySql);
ddlInstitution.DataTextField = "institution";
ddlInstitution.DataValueField = "institutionid";
ddlInstitution.DataSource = dr;
ddlInstitution.DataBind();
}
protected void ddlInstitution_SelectedIndexChanged(object sender, EventArgs e)
{
// call a method to populate the template ddl
populateDdlTemplate();
}
protected void populateDdlTemplate()
{
CRUD myCrud = new CRUD();
string mySql = #"select internDocId, DocName
from internDoc
where institutionId = #institutionId";
Dictionary<string, object> myPara = new Dictionary<string, object>();
myPara.Add("#institutionId", ddlInstitution.SelectedItem.Value);
SqlDataReader dr = myCrud.getDrPassSql(mySql, myPara);
ddlTemplate.DataTextField = "DocName";
ddlTemplate.DataValueField = "internDocId";
ddlTemplate.DataSource = dr;
ddlTemplate.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
CRUD myCrud = new CRUD();
string mySql = #"select* from intern
where institutionId = #institutionId"/*+#"select internDocId,DocName from internDoc where internDocId=internDocId"*/;
Dictionary<string, object> myPara = new Dictionary<string, object>();
myPara.Add("#institutionId", ddlInstitution.SelectedItem.Value);
//myPara.AsEnumerable(#"internDocId");
SqlDataReader dr = myCrud.getDrPassSql(mySql, myPara);
gvData.DataSource = dr;
gvData.DataBind();
}
protected void btnGenerateTemplate_Click(object sender, EventArgs e)
{
wordT();
}
private static DataTable GetRecipients()
{
//Creates new DataTable instance.
DataTable table = new DataTable();
//Loads the database.
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + #"../../CustomerDetails.mdb");
//Opens the database connection.
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from intern", conn);
//Gets the data from the database.
adapter.Fill(table);
//Releases the memory occupied by database connection.
adapter.Dispose();
conn.Close();
return table;
}
public void wordT()
{
for (int i = 0; i <= gvData.Rows.Count - 1; i++)
{
String internId = gvData.Rows[i].Cells[0].Text;
String fullName = gvData.Rows[i].Cells[7].Text;
String cell = gvData.Rows[i].Cells[8].Text;
String email = gvData.Rows[i].Cells[9].Text;
Syncfusion.DocIO.DLS.WordDocument document = new Syncfusion.DocIO.DLS.WordDocument(Server.MapPath(getPath()));
//Deleting null fields
document.MailMerge.RemoveEmptyParagraphs = true;
string[] fieldNames = new string[] { "fullName", "internId", "email", "cell" };
string[] fieldValues = new string[] { fullName, internId, email, cell };
// mail merge
document.MailMerge.Execute(fieldNames, fieldValues);
//Saves
document.Save(Server.MapPath("~/myDoc/" + email + ".docx"));
document.Close();
}
// pass message to user notifying of successfull operation
lblOutput.Text = "Word Doc output generated successfully!";
}
public string getPath()
{
DirectoryInfo di = new DirectoryInfo(#"C:\projects\unSupervisorApp\Uploads\");
foreach (var d in di.EnumerateDirectories())
{
foreach (var fi in d.EnumerateFileSystemInfos())
{
if (fi.Name == (ddlTemplate.DataTextField))
{
return fi.FullName.Replace(fi.Name, "");
}
}
}
return di.FullName;
}
}//cls
the problem:
‎1-'C:/projects/unSupervisorApp/Uploads/' is a physical path but was expected to be a virtual path.‎
2- and sometime it gives me that it i can not find the file in EnumerateDirectories.
but i get the first one the most.
getFile
getPath
path of folder + ddlselectedItem.text

get value into query from edit mode in gridview

I have a simple gridview, 2 columns. The first column is a numeric value. The second column is based on a selected value from a drop down list. I have the drop down list working, but when I go to update the table, I get an error :
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
The offending line is 55
Line 53: {
Line 54: string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
Line 55: string AnnoNum = gvSummary.DataKeys[e.RowIndex].Value.ToString();
and here is the code behind for the webform:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace SHCAnnotation
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string query = "select distinct Unit from vw_KmartBU";
SqlCommand cmd = new SqlCommand(query);
dlBU.DataSource = GetData(cmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
//dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string AnnoNum = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [Business Unit] = #BU where [Annotation Number] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnoNum);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
private void BindData()
{
string query = "select [Annotation Number], [Business Unit] as Unit from vw_GridviewSource";
SqlCommand cmd = new SqlCommand(query);
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
}
What I need to do is get the value in first column "Annotation Number" and use it in the where clause of my update. So I would need update vw_GridviewSource set [Business Unit] = 'Accessories' where [Annotation Number] = '123456'
Accessories would have been the selection from the drop down list and 123456 would have been in the text box when I selected that row for editing.
Your gridview is missing DataKeyNames. It may look like:
<asp:GridView ID="gvSummary"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="AnnoNum, MyOtherKey1, MyOtherKey2"
... ... ...
DataKeyNames property is an array of strings. You can find more in MSDN

Want to show a message on mouse hover on a date

I have used the following .net code. Which shows the holiday date which I store in database.
But i want to show some message when I hover the mouse on the date.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string connection = #"server=TOPHAN-PC; Database=Tophan;uid=sa;pwd=123";
SqlConnection con = null;
protected DataSet dsHolidays;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con = new SqlConnection(connection);
Calendar1.VisibleDate = DateTime.Today;
FillHolidayDataset();
}
}
protected void FillHolidayDataset()
{
DateTime firstDate = new DateTime(Calendar1.VisibleDate.Year, Calendar1.VisibleDate.Month, 1);
DateTime lastDate = GetFirstDayOfNextMonth();
dsHolidays = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (Calendar1.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = Calendar1.VisibleDate.Year + 1;
}
else
{
monthNumber = Calendar1.VisibleDate.Month + 1;
yearNumber = Calendar1.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)
{
DataSet dsMonth = new DataSet();
try
{
//ConnectionStringSettings cs;
//cs = ConfigurationManager.ConnectionStrings["ConnectionString1"];
//String connString = cs.ConnectionString;
//SqlConnection dbConnection = new SqlConnection(connString);
String query = "SELECT CDate FROM calender WHERE CDate >= #firstDate AND CDate < #lastDate";
con.Open();
SqlCommand dbCommand = new SqlCommand(query, con);
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));
dbCommand.Parameters.Add(new SqlParameter("#lastDate", lastDate));
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(dbCommand);
sqlDataAdapter.Fill(dsMonth);
}
catch
{ }
return dsMonth;
}
protected void Calendar1_VisibleMonthChanged(object sender,
MonthChangedEventArgs e)
{
FillHolidayDataset();
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
try
{
DateTime nextDate;
if (dsHolidays != null)
{
foreach (DataRow dr in dsHolidays.Tables[0].Rows)
{
nextDate = (DateTime)dr["CDate"];
if (nextDate == e.Day.Date)
{
e.Cell.BackColor = System.Drawing.Color.Pink;
}
}
}
}
catch
{ }
}
}
By using this code,I find out that it highlighted the date with the color but I want some message when I move the mouse on the Date.
you can do it by this:
$(document).ready(function()
{
$("#holiday").hover(function () {
//Show whatever message on hover in
},
function () {
//Show whatever message on hover out
}
); });

asp.net url generation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Web.Services;
using System.IO;
namespace T_Smade
{
public partial class ConferenceManagement : System.Web.UI.Page
{
volatile int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
GetSessionList();
}
public void GetSessionList()
{
string secondResult = "";
string userName = "";
try
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
userName = HttpContext.Current.User.Identity.Name;
}
SqlConnection thisConnection = new SqlConnection(#"data Source=ZOLA-PC;AttachDbFilename=D:\2\5.Devp\my DB\ASPNETDB.MDF;Integrated Security=True");
thisConnection.Open();
SqlCommand secondCommand = thisConnection.CreateCommand();
secondCommand.CommandText = "SELECT myApp_Session.session_id FROM myApp_Session, myApp_Role_in_Session where myApp_Role_in_Session.user_name='" + userName + "' and myApp_Role_in_Session.session_id=myApp_Session.session_id";
SqlDataReader secondReader = secondCommand.ExecuteReader();
while (secondReader.Read())
{
secondResult = secondResult + secondReader["session_id"].ToString() + ";";
}
secondReader.Close();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT * FROM myApp_Session;";
SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
test.Controls.Add(GetLabel(thisReader["session_id"].ToString(), thisReader["session_name"].ToString()));
string[] compare = secondResult.Split(';');
foreach (string word in compare)
{
if (word == thisReader["session_id"].ToString())
{
test.Controls.Add(GetButton(thisReader["session_id"].ToString(), "Join Session"));
}
}
}
thisReader.Close();
thisConnection.Close();
}
catch (SqlException ex)
{
}
}
private Button GetButton(string id, string name)
{
Button b = new Button();
b.Text = name;
b.ID = "Button_" + id + i;
b.Command += new CommandEventHandler(Button_Click);
b.CommandArgument = id;
i++;
return b;
}
private Label GetLabel(string id, string name)
{
Label tb = new Label();
tb.Text = name;
tb.ID = id;
return tb;
}
protected void Button_Click(object sender, CommandEventArgs e)
{
Response.Redirect("EnterSession.aspx?session=" + e.CommandArgument.ToString());
}
}
when users click from this page the next page is generated as
www.mypage/Entersession.aspx?session=session_id
but i'd rather to have it like
www.mypage/Entersession.aspx?session=session_name
both session_id and session_name are from the database
any idea?
}
Just change
test.Controls.Add(GetButton(thisReader["session_id"].ToString(), "Join Session"));
to
test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session"));
The change you're looking for takes place in where you use your GetButton method
Change:
test.Controls.Add(GetButton(thisReader["session_id"].ToString(), "Join Session"));
To:
test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session"));
Your first input parameter to GetButton is being mapped to the CommandArgument. So passing session_name in rather than session_id will do the trick.
Is this what you are looking for? Changing CommandArgument to name? It's a very, very easy fix.
Update
You could add a commandArgument parameter to GetButton().
private Button GetButton(string id, string name, string commandArgument)
{
Button b = new Button();
b.Text = name;
b.ID = "Button_" + id + i;
b.Command += new CommandEventHandler(Button_Click);
b.CommandArgument = commandArgument; // this changed to commandArgument
i++;
return b;
}
GetButton(thisReader["session_id"].ToString(), "Join Session", thisReader["session_name"].ToString())

Resources