Hi i am new here i just want to ask question for this code.
i am making a condition on my new buttom that generate Enumber= Employee Number.
i have database but no data record yet. if i press my new buttom my sql statement will select he last record on my data but i don't have yet data so i am trying to make a condition.
if Enumber is empty in database it should return and give the new Enumber on my textbox = txtEnumber.Text = "100000".
i hope you understand my problem.
con.Open();
cmd = new SqlCommand("SELECT TOP 1 Enumber FROM Employee ORDER BY Enumber DESC ", con);
dr = cmd.ExecuteReader();
dr.Read();
if (dr["Enumber"] == null) // Error: "Invalid attempt to read when no data is present."
{
txtEnumber.Text = "100000";
return;
}
else
{
String a = dr["Enumber"].ToString();
txtEnumber.Text = ("");
for (int i = 0; i < 1; i++)
{
string val = a.Substring(1, a.Length - 1);
int newnumber = Convert.ToInt32(val) + 1;
a = newnumber.ToString("100000");
}
txtEnumber.Text = a;
}
con.Close();
Since you don't have any row in your case, you can't iterate your reader. Instead of that, you can use ExecuteScalar which returns null as an object if there is no data in first column of the first row since your query returns as SELECT TOP 1...
var result = cmd.ExecuteScalar();
if(result == null)
{
txtEnumber.Text = "100000";
}
You should check whether there are rows first. dr.Read() returns whether the DataReader has rows, use it.
Your DataReader returns no results...
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
// read data for first record here
}
If you have more than one result, use a 'while' loop.
while (dr.Read()) {
// read data for each record here
}
You should use dr.HasRows to check whether there is data or not.
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
dataTable.Load(dr);
}
If you have more than one result, use a 'foreach' loop.
foreach (DataRow Drow in datatable.Rows)
{
// read data for each record here
}
Try This is Worked..
Related
I am trying to list all data in a table, but it only returns the first row, it doesn't loop the whole table.
i need to return the data as strings, because I will use it in a ASMX web service.
And the xml schema only returns the first row
<String> data in row 1<String>
i want it to return somthing like this:
<String> data in row 1<String>
<String> data in row 2<String>
<String> data in row 3<String>
and row 1 to n rows....
I have tested the sql statment in VS2012 query builder and there it works fine.
so i need to list out all the data in a way.
Here is my Code
public String finAllCompaniesForSpesficuserByUserId(String userid)
{
List<String> l = new List<String>();
try
{
String sql = "SELECT Companies.Name FROM UsersInCompanies INNER JOIN Companies ON UsersInCompanies.CompanyId = Companies.CompanyId WHERE UsersInCompanies.UserId ='" + userid + "'";
con = new SqlConnection(cs);
cmd = new SqlCommand(sql, con);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(table);
con.Open();
dr = cmd.ExecuteReader();
dr.Read();
//while (dr.Read())
//{
// l.Add(dr["Name"].ToString());
//}
foreach (DataRow row in table.Rows)
{
return row["Name"].ToString();
}
}
finally
{
if (con != null)
con.Close();
}
/*
foreach (string p in l)
{
return p;
}
*/
return null;
}
Can someone point me in the right direction or give me an examples?
foreach (DataRow row in table.Rows)
{
return row["Name"].ToString();
}
you are returning from very first iteration itself.
Instead of returning immediately in the for-loop either use a yield statement (and change the return type to IEnumerable<String> - which just moves the for loop out of the function and somewhere else) or use a StringBuilder to build the resulting string.
StringBuilder sb = new StringBuilder(table.Rows.Count * 30); /* 30 is arbitrary */
foreach (DataRow row in table.Rows)
{
// yes 3 separate calls are correct
sb.Append("<String>");
sb.Append(row["Name"].ToString())
sb.Append("</String>\n");
}
/* after closing, cleaning up */
return sb.ToString();
Try this
var temp= "<String>" +
string.Join("</String>\n<String>", dt.Rows.Cast<DataRow>().Select(x => x["Name"].ToString())) +
"</String>";
I want to find the index of a string in a DataGridView row and here is my code:
DataGridViewRow row = dgvVisual.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => (string)r.Cells[0].Value == "9");
but the return value of row is null instead of a DataGridViewRow, how to solve this problem?
The Whole code is here:
SqlCommand cmd;
cmd = new SqlCommand("select * from MyTable , SqlConnection);
SqlDataReader read;
read = cmd.ExecuteReader();
while (read.Read())
{
int ColIndex= int.Parse(read["ColumnName"].ToString()) + 1;
int RowIndex = -1;
DataGridViewRow row = dgvVisual.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => (string)r.Cells[0].Value == (string)read["ColumnNameB"].ToString().Trim());
if (row != null)
RowIndex = row.Index;
DataGridViewCheckBoxCell chkbxCell = (DataGridViewCheckBoxCell)dgvVisual[ColIndex, RowIndex];
chkbxCell.Value = true;
}
read.Close();
Problem solved as there was some problem in the database and the read back was not correct.
It returns null because of FirstOrDefault(), which means that it didn't find any results with your query. Ensure that you really have any rows with that condition.
Without seeing your data it's hard to say if your lambda query is right.
My code:
string sqlQuery1 = "select * from employees where depid=6";
SqlDataReader Dr1 = dbconn.RunQueryReturnDataReader(sqlQuery1);
if(Dr1.read()) { //or if (Dr1["empname"] != DBNull.Value)
while (Dr1.Read())
{
Label1.Text = Dr1["empname"].ToString();
Label2.Text = Dr1["empdes"].ToString();
...
}
Dr1.Close();
}
else {
Label1.text = "defaultValue";
Label2.text = "defaultValue";
...
}
I just want to check SqlDataReader has no records to display. If no records ,the labels should showdefault values preassigned by me or If has record display datareader value on label. (Assume either SqlDataReader has 1 recode or has norecord only)
How can I check first datareader hasRow or not?
I have tried two ways as above code.
if(Dr1.read()) - this way working fine. But after execute If statement ,it has no value to display on labels , since read() will increase the pointer. As a result label1 ,Label2.. Nothing display.
if (Dr1["empname"] != DBNull.Value)
This way generate an exception when Sqldatareader has norows.
error: System.InvalidOperationException: Invalid attempt to read when no data is present
Please help me. tx
try...
if(Dr1.HasRows)
{
//....
}
if (Dr1 == null || !Dr1.HasRows) {
// Do something
}
I am trying to create a login form on my ASP.NET website. Currently, there's some problem. I am trying to incorporate the functionality such that the logged in user has the previlige to view only his profile. The code on the login page is this:
business.clsprofiles obj = new business.clsprofiles();
Int32 a = obj.logincheck(TextBox3.Text, TextBox4.Text);
if (a == -1)
{
Label1.Text = "Username/Password incorrect";
}
else
{
Session["cod"]= a;
Response.Redirect("profile.aspx");
}
After logging in, the user is moved to the page where the person can view his profile once logged in. Session is obtaining the value correctly of the logged in person from the login-page and successfully passing it on to the next page. But here on this profile page an error occurs and I think there is problem somewhere in the grid_bind() method below
public void grid_bind()
{
business.clsprofiles obj = new business.clsprofiles();
List<business.clsprofilesprp> objprp = new List<business.clsprofilesprp>();
Int32 z = Convert.ToInt32(Session["cod"]);
objprp = obj.fnd_profiles(z); //This line of code is passing an integer as required but does not get the desired result from the database
GridView1.DataSource = objprp;
GridView1.DataBind();
}
As the error in business logic says, " invalid attempt to read when no data is present in dr"
public List<clsprofilesprp> fnd_profiles(Int32 id)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("fndpro", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
List<clsprofilesprp> obj = new List<clsprofilesprp>();
while(dr.HasRows)
{
clsprofilesprp k = new clsprofilesprp();
k.id = Convert.ToInt32(dr[0]);//Something wrong here?
k.name = dr[1].ToString();
k.password = dr[2].ToString();
k.description = dr[3].ToString();
k.created = Convert.ToDateTime(dr[4]);
k.modified = Convert.ToDateTime(dr[5]);
obj.Add(k);
}
dr.Close();
cmd.Dispose();
con.Close();
return obj;
}lesprp k = new clsprofilesprp();
k.id = Convert.ToInt32(dr[0]);//Something wrong here?
k.name = dr[1].ToString();
k.password = dr[2].ToString();
k.description = dr[3].ToString();
k.created = Convert.ToDateTime(dr[4]);
k.modified = Convert.ToDateTime(dr[5]);
obj.Add(k);
}
dr.Close();
cmd.Dispose();
con.Close();
return obj;
You have to call DataReader.Read to fetch the result:
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
// ...
DataReader.Read returns a boolean, so if you have more than 1 result, you can do:
While (dr.Read())
{
// read data for each record here
}
Moreover, you're trying to access the dr data when there's none in this part of the code:
k.id = Convert.ToInt32(dr[0]);//Something wrong here?
k.name = dr[1].ToString();
k.password = dr[2].ToString();
k.description = dr[3].ToString();
k.created = Convert.ToDateTime(dr[4]);
k.modified = Convert.ToDateTime(dr[5])
You've got a problem with...
while (dr.HasRows)
{
/* If this loop is entered, it will run
* indefinitely until the datareader miraculously
* loses all its rows in a hole somewhere */
}
This will either never enter, or will create an infinite loop... it's either got no rows or it has rows. What I think you meant was:
while (dr.Read())
{
/* Do something with the current record */
}
dr.Read() loops to the next record and returns true or false depending on if there's a record to be read or not. When the data reader is initialized, the first record is not selected. It has to be selected by calling dr.Read() which will then return true if a first row is found, and indeed will return true until Read() is called when currently on the last row - i.e. there's no more rows left to read.
dr.HasRows is just a property that tells you if the datareader contains rows... which if it does will keep having rows from here until eternity. For instance, you would use this if you wanted to do something in the event it has rows and something else in the event it doesn't:
if (dr.HasRows)
{
while (dr.Read())
{
/* Display data for current row */
}
}
else
{
Console.WriteLine("I didn't find any relevant data.");
}
You are trying to access a row in the datareader though there are no rows. i.e
if the dr doesn't enter the while loop then there are no rows in the datareader, however you are still accessing the fields where you have a comment "//Something wrong here? ".
I need to iterate through a DataTable. I have an column there named ImagePath.
When I am using DataReader I do it this way:
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
while (dr.Read())
{
TextBox1.Text = dr["ImagePath"].ToString();
}
How can I achieve the same thing using DataTable?
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
foreach(DataRow row in dt.Rows)
{
TextBox1.Text = row["ImagePath"].ToString();
}
...assumes the connection is open and the command is set up properly. I also didn't check the syntax, but it should give you the idea.
foreach (DataRow row in myDataTable.Rows)
{
Console.WriteLine(row["ImagePath"]);
}
I am writing this from memory.
Hope this gives you enough hint to understand the object model.
DataTable -> DataRowCollection -> DataRow (which one can use & look for column contents for that row, either using columnName or ordinal).
-> = contains.
You can also use linq extensions for DataSets:
var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
{
TextBox1.Text = imgPath;
}
There are already nice solution has been given. The below code can help others to query over datatable and get the value of each row of the datatable for the ImagePath column.
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var theUrl = dataTable.Rows[i]["ImagePath"].ToString();
}
The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:
foreach (DataRow row in dtData.Rows)
{
if (row["Column_name"].ToString() == txtBox.Text)
{
// Getting the sequence number from the textbox.
string strName1 = txtRowDeletion.Text;
// Creating the SqlCommand object to access the stored procedure
// used to get the data for the grid.
string strDeleteData = "Sp_name";
SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;
// Running the query.
conn.Open();
cmdDeleteData.ExecuteNonQuery();
conn.Close();
GetData();
dtData = (DataTable)Session["GetData"];
BindGrid(dtData);
lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
txtRowDeletion.Text = "";
break;
}
else
{
lblMsgForDeletion.Text = "The row is not present ";
}
}
foreach(DataGridViewRow row in dataGridView1){ var a = row.Cells[4].Value.ToString(); }