Issue with List.Add(): it only saves the last added item, it binds the last data repeatedly, please someone help me to clear it. I am trying out in mvc 4 as Begineer. I am also struggling with basic of mvc 4. thank u in advance.
var modelList = new List<MyCourseData>();
string batchid = System.Web.HttpContext.Current.Request.QueryString["batchid"];
SqlConnection con = null;
string result = "";
DataSet ds = null;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select * from [Student].[dbo].[tbl_batch] where batchid=#batchid", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#batchid", batchid);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new MyCourseData();
var classdates = ds.Tables[0].Rows[i]["class_dates"].ToString();
int j = 0;
// string[] parts = classdates.Split(',');
foreach (string CourseDates in classdates.Split(','))
{
model.batchid = ds.Tables[0].Rows[i]["batchid"].ToString();
model.course = ds.Tables[0].Rows[i]["course"].ToString();
model.trainer = ds.Tables[0].Rows[i]["trainer"].ToString();
model.class_dates = CourseDates;
modelList.Add(model);
}
}
return modelList;
This happens because you are adding the same instance of MyCourseData in the list with value changing in every iteration.
You need to create new instance of MyCourseData for every iteration,
var modelList = new List<MyCourseData>();
string batchid = System.Web.HttpContext.Current.Request.QueryString["batchid"];
SqlConnection con = null;
string result = "";
DataSet ds = null;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select * from [Student].[dbo].[tbl_batch] where batchid=#batchid", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#batchid", batchid);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var classdates = ds.Tables[0].Rows[i]["class_dates"].ToString();
int j = 0;
// string[] parts = classdates.Split(',');
foreach (string CourseDates in classdates.Split(','))
{
var model = new MyCourseData();
model.batchid = ds.Tables[0].Rows[i]["batchid"].ToString();
model.course = ds.Tables[0].Rows[i]["course"].ToString();
model.trainer = ds.Tables[0].Rows[i]["trainer"].ToString();
model.class_dates = CourseDates;
modelList.Add(model);
}
}
return modelList;
}
Related
below is my code in which in want to use dropdownlist but i am unable to call its id: error showing that object require for static method.
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCity(string prefixText)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["mycon"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("select * from tbl_group where Group_Name=" + drpgovtypelcns1.Selecteditem.Text, con);
cmd.Parameters.AddWithValue("#Group_Name", prefixText);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
List<string> CityNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CityNames.Add(dt.Rows[i][1].ToString());
}
return CityNames;
}
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\user\Documents\Visual Studio 2010\Projects\Timetable\Timetable\bin\Debug\timetabledata.accdb";
//create the database query
string query = "SELECT * FROM relation";
OleDbConnection conn = new OleDbConnection(conString);
conn.Open();
// create the DataSet
DataSet ds = new DataSet();
// create the adapter and fill the DataSet
OleDbDataAdapter adapter;
adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(ds);
int f = ds.Tables[0].Rows.Count;
int i;
for (i = 0; i < f; i++)
{
// create the database query
string query1 = "SELECT * FROM [time] Where classid= '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
DataSet ds1 = new DataSet();
OleDbDataAdapter adapter1;
adapter1 = new OleDbDataAdapter(query1, conn);
adapter1.Fill(ds1);
MessageBox.Show(ds1.Tables[0].Rows[0].ItemArray[0].ToString());
}
the result that i get not true in message box that i want the id of all rows having the same classid but in message box that i use just to verification before o continue i see the id of time table without be consider where
Shouldn't this part be changed from...
string query1 = "SELECT * FROM [time] Where classid+ '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
to...
string query1 = "SELECT * FROM [time] Where classid = '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
You seem to be using a plus symbol (+) instead of equals (=).
Give this a shot:
public DataSet GetRelations()
{
using (var connection = new OleDbConnection(ConnectionString))
{
connection.Open();
using (var adapter = new OleDbDataAdapter("SELECT * FROM [relation]", connection))
{
var results = new DataSet();
adapter.Fill(results);
return results;
}
}
}
public DataSet GetTimeResults()
{
DataSet dsRelations = GetRelations();
var dsResults = new DataSet();
using (var connection = new OleDbConnection(ConnectionString))
{
connection.Open();
foreach (DataRow row in dsRelations.Tables[0].Rows)
{
using (var command = new OleDbCommand("SELECT * FROM [time] Where classid = ?", connection))
{
// not entirey sure what the value of row.ItemArray[2] is ?
command.Parameters.Add(row.ItemArray[2]);
using (var adapter = new OleDbDataAdapter(command))
{
adapter.Fill(dsResults);
}
}
}
}
return dsResults;
}
Just invoke it and use it as you see fit:
public void Test()
{
DataSet dsTimeResults = GetTimeResults();
// Do whatever you need with the results
}
I have an issue with assigning values.
string userlanguages = string.Empty;
try
{
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] ='" + Class1.EmployeeId + "'", objcon);
if (objcon.State == ConnectionState.Closed) objcon.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDS = new DataSet();
adp.Fill(myDS);
userlanguages = myDS.Tables[0].Rows[0]["[s_langName]"].ToString();
}
catch (SqlException exc)
{
Response.Write(exc.Message);
}
finally
{
objcon.Close();
Class1.langKnwn = userlanguages;
}
}
Suppose, Here the myDs contains three values. Then how will i assign them to a single string(in this case 'userlanguages'). I am using the Class1.langKnwn in another page to display the user selected languages(which may be more than 1 language in many cases).
Please help me.
How about somethig like
List<string> languages = new List<string>();
for (int iRow = 0; iRow < myDS.Tables[0].Rows.Count; iRow++)
languages.Add(myDS.Tables[0].Rows[iRow]["[s_langName]"].ToString());
userlanguages = String.Join(",", languages);
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] ='" + Class1.EmployeeId + "'", objcon);
if (objcon.State == ConnectionState.Closed) objcon.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDS = new DataSet();
adp.Fill(myDS);
for(int ndx=0;ndx<myDS.Tables[0].Rows.Count;ndx+=1)
{
if(ndx==0)
{
userlanguages = myDS.Tables[0].Rows[ndx]["[s_langName]"].ToString();
}
else
{
userlanguages = userlanguages+","+ myDS.Tables[0].Rows[ndx]["[s_langName]"].ToString();
}
}
userlanguages = string.Join(",", myDS.Tables[0].AsEnumerable()
.Select(row => row.Field<string>("[s_langName]"))
.ToArray());
If I understand your question correctly, using SqlDataReader could be better option in your case.
using (SqlConnection objcon= new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT [s_langName] from [dbo].[tx_UserLanguages] WHERE [s_ID] = #id", objcon);
cmd.Parameters.AddWithValue("#id", Class1.EmployeeId);
connection.Open();
SqlDataReader reader = cmd .ExecuteReader();
string userlanguages = string.Empty;
while (reader.Read())
{
string str = reader.GetString(0);
userlanguages = String.Join(",", userlanguages);
}
reader.Close();
}
And you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Try this
Use using System.Text; namesapce
and then write that code in your block
StringBuilder sb = new StringBuilder();
for (int iRow = 0; iRow < myDS.Tables[0].Rows.Count; iRow++)
{
sb.Append(myDS.Tables[0].Rows[iRow]["[s_langName]"].ToString());
sb.Append(",");
}
// to get the string at the end
string myString = sb.ToString();
myString= myString.Substring(0, myString.Length - 1);
Friends expecting ur suggetions to the below code. Instead of taking dtr1( DatatableReader) it is taking outside loop dtr(DataTableReader) Table.
protected void GetStudReport(Object o, EventArgs e)
{
if (mycon.State != ConnectionState.Open)
{
List<string> lstQstn = new List<string>();
mycon.Open();
cmd = new MySqlCommand("SELECT * from scord_mark_table where stu_ID='" + drpDnSearch3.SelectedValue + "'", mycon);
MySqlDataReader rdr1=cmd.ExecuteReader();
DataSet ds=new DataSet();
DataTable dtScrTbl=new DataTable();
dtScrTbl.Load(rdr1);
ds.Tables.Add(dtScrTbl);
rdr1.Close();
cmd = null;
int i = 0;
Dictionary<string, string> dctSub = new Dictionary<string, string>();
**using (DataTableReader dtr = ds.CreateDataReader())**
{
while (dtr.Read())
{
lstQstn.Add(dtr["test_id"].ToString());
while (i <= lstQstn.Count())
{
MySqlCommand cmd2 = new MySqlCommand("SELECT test_id,subject_id from qution_no_table where test_id='" + lstQstn[i].ToString() + "'", mycon);
MySqlDataReader rdr2 = cmd2.ExecuteReader();
DataTable dtQsNoTbl = new DataTable();
dtQsNoTbl.Load(rdr2);
ds.Tables.Add(dtQsNoTbl);
**using (DataTableReader dtr1 = ds.CreateDataReader())**
{
while (dtr1.Read())
{
dctSub.Add(dtr1["test_id"].ToString(), dtr1["subject_id"].ToString()); // **here it is taking table scord_mark_table instead of dtr1's qution_no_table**
}
rdr2.Close();
break;
}
}
//cmd2 = null;
i++;
}
}
No, it's not - it's returning a new DataTableReader hooked to ALL of the existing tables (including the one you created before the first loop).
Try specifying the DataTable you want the readers attached to:
using (DataTableReader dtr = ds.CreateDataReader(dtScrTbl))
and
using (DataTableReader dtr1 = ds.CreateDataReader(dtQsNoTbl))
I am supposed to read tags from multiple devices but using single port.
I am able to do so, but while I read one device keeping tag in front of it another device does not read into string unless I remove the tag.
I need to read the tags from all devices simultaneously.
It works on hyperterminal so the problem is in code
My Code:
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//int bytes = serialPort1.BytesToRead;
////create a byte array to hold the awaiting data
//byte[] comBuffer = new byte[bytes];
////read the data and store it
//serialPort1.Read(comBuffer, 0, bytes);
//MessageBox.Show(comBuffer[bytes]);
////display the data to the user
////DisplayData(MessageType.Incoming, ByteToHex(comBuffer) + "\n");
//serialPort1.Dispose();
//serialPort1.Close();
//if (serialPort1.IsOpen)
//{
// serialPort1.ReadExisting();
// serialPort1.Close();
//}
string data = serialPort1.ReadLine();
data = data.Substring(2, 2);
if (data == "03")
{
//while (data == "03")
//{
string data1 = serialPort1.ReadLine();
data1 = data1.Substring(4, 10);
for (int b = 0; b < dataGridView3.Rows.Count; b++)
{
string floorno = dataGridView3.Rows[b].Cells[0].Value.ToString();
SqlConnection conn = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd = new SqlCommand("Select Floor,RfidTag,DeviceId from LiftMonitor where Floor='" +
floorno + "'and DeviceId='03'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
SqlCommandBuilder commandBuilder1 = new SqlCommandBuilder(da);
da.Fill(ds, "LiftMonitor");
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
DataRow dr = ds.Tables[0].Rows[j];
string rfidtag = dr["RfidTag"].ToString();
if (rfidtag == data1)
{
dataGridView3.ClearSelection();
dataGridView3.Rows[b].Selected = true;
goto abc;
timer1.Start();
SqlConnection conn1 = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd1 = new SqlCommand(" Select Timer from Setting ", conn1);
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da1);
da1.Fill(ds1, "Timer");
for (int k = 0; k < ds1.Tables[0].Rows.Count; k++)
{
DataRow dr1 = ds1.Tables[0].Rows[k];
string timer = dr1["Timer"].ToString();
int timer2 = Convert.ToInt32(timer);
timeConversion = timer2 * 1000;
if (timeConversion.Equals(timer1.Interval))
{
timer1.Tick += new System.EventHandler(timer1_Tick);
}
}
}
else
{
}
}
}
//}
}
if (data == "04")
{
//while (data == "04")
//{
string data1 = serialPort1.ReadLine();
//data1 = data1.Substring(1, 2);
data1 = data1.Substring(4, 10);
for (int b = 0; b < dataGridView4.Rows.Count; b++)
{
string floorno = dataGridView4.Rows[b].Cells[0].Value.ToString();
SqlConnection conn = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd = new SqlCommand("Select Floor,RfidTag,DeviceId from LiftMonitor where Floor='" +
floorno + "' and DeviceId='04'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
SqlCommandBuilder commandBuilder1 = new SqlCommandBuilder(da);
da.Fill(ds, "LiftMonitor");
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
DataRow dr = ds.Tables[0].Rows[j];
string rfidtag = dr["RfidTag"].ToString();
if (rfidtag == data1)
{
dataGridView4.ClearSelection();
dataGridView4.Rows[b].Selected = true;
goto abc;
timer1.Start();
SqlConnection conn1 = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd1 = new SqlCommand(" Select Timer from Setting ", conn1);
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da1);
da1.Fill(ds1, "Timer");
for (int k = 0; k < ds1.Tables[0].Rows.Count; k++)
{
DataRow dr1 = ds1.Tables[0].Rows[k];
string timer = dr1["Timer"].ToString();
int timer2 = Convert.ToInt32(timer);
timeConversion = timer2 * 1000;
if (timeConversion.Equals(timer1.Interval))
{
timer1.Tick += new System.EventHandler(timer1_Tick);
}
}
}
else
{
}
}
}
//}
}
if (data == "05")
{
//while (data == "05")
//{
string data1 = serialPort1.ReadLine();
data1 = data1.Substring(4, 10);
for (int b = 0; b < dataGridView5.Rows.Count; b++)
{
string floorno = dataGridView5.Rows[b].Cells[0].Value.ToString();
SqlConnection conn = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd = new SqlCommand("Select Floor,RfidTag,DeviceId from LiftMonitor where Floor='" +
floorno + "'and DeviceId='05'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
SqlCommandBuilder commandBuilder1 = new SqlCommandBuilder(da);
da.Fill(ds, "LiftMonitor");
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
DataRow dr = ds.Tables[0].Rows[j];
string rfidtag = dr["RfidTag"].ToString();
if (rfidtag == data1)
{
dataGridView5.ClearSelection();
dataGridView5.Rows[b].Selected = true;
//break;
goto abc;
timer1.Start();
SqlConnection conn1 = new SqlConnection(dba.GetConnectionString());
SqlCommand cmd1 = new SqlCommand(" Select Timer from Setting ", conn1);
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da1);
da1.Fill(ds1, "Timer");
for (int k = 0; k < ds1.Tables[0].Rows.Count; k++)
{
DataRow dr1 = ds1.Tables[0].Rows[k];
string timer = dr1["Timer"].ToString();
int timer2 = Convert.ToInt32(timer);
timeConversion = timer2 * 1000;
if (timeConversion.Equals(timer1.Interval))
{
timer1.Tick += new System.EventHandler(timer1_Tick);
}
}
}
//else
//{
// break;
//}
}
}
}
}