In my Page I am fetching a value from the Database & filling the values in the DataTable. I am then comparing that values with the mac String in the IF.
Based upon the condition in the Query there will be no records fetched, it is stuck in the IF condition and throws the No row at Position 0 Exception rather than going into the Else part.
My code is:
string mac = GetMac();
string Qry = "Select VUserid,Password from passtable where VUserid='" + UserName.Text + "' and Flag='A'";
string qry = "Select VUserid,Password from passtable where Flag='A'";
string strq = "Select Mac_id from Sysinfo Where Appflag='A'";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EvalCon"].ConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand(Qry, conn);
SqlCommand cmd1 = new SqlCommand(qry, conn);
SqlCommand cmd2 = new SqlCommand(strq, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataAdapter daa = new SqlDataAdapter(cmd1);
SqlDataAdapter dap = new SqlDataAdapter(cmd2);
DataTable dt = new DataTable();
DataTable dtt = new DataTable();
DataTable tab = new DataTable();
da.Fill(dt);
daa.Fill(dtt);
dap.Fill(tab);
for (int i = 0; i < tab.Rows.Count; i++)
{
for (int x = 0; x <= dtt.Rows.Count - 1; x++)
{
if (mac == tab.Rows[i]["Mac_id"].ToString() || tab.Rows.Count != 0)
{
if (UserName.Text == dtt.Rows[x]["VUserid"].ToString() && Password.Text == dtt.Rows[x]["Password"].ToString())
{
Response.Redirect("~/Changepass.aspx");
break;
}
else
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Invalid Username or Password !!!";
}
}
else
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Invalid Access Point for Evaluation !!!";
}
}
}
}
finally
{
conn.Close();
conn.Dispose();
}
}
First of all, you may want to give some more meaningful names to your variables.
On a side note, you may want to change your for loops into a foreach loop:
foreach (DataRow tabRow in tab.Rows.Count)
{
foreach (DataRow dttRow in dtt.Rows.Count)
{
// logic here
// tab.Rows[i]["Mac_id"] becomes tabRow["Mac_id"]
// and
// dtt.Rows[x]["VUserid"] becomes dttRow["VUserid"]
// and so on...
}
}
This way if there are no records fetched it won't go in.
After that, you may want to check the conditions on RowCount > 0 for the datatables before going inside the loops and act outside the loop if the RowCount is 0.
Just swap your OR condition in If statement:
if (tab.Rows.Count != 0 || mac == tab.Rows[i]["Mac_id"].ToString())
{
...
...
}
If you need to check against a null result I'd wrap my if statement in another if statement that does a simple check for a null result before doing anything else. Something like this will check if it's not null:
if(tab.rows[i]["Mac_id"] != null)
{
//logic here
}
You could add this into your current if statement check so:
if(mac == tab.Rows[i]["Mac_id"].ToString() || tab.Rows.Count != 0)
becomes:
if(mac == tab.Rows[i]["Mac_id"].ToString() || tab.Rows.Count != 0 && tab.rows[i]["Mac_id"] != null)
Though as Tallmaris says it might be better to restructure it using a foreach loop instead.
Related
I am trying to filter my database values that matches my condition.
Here is code:
con = new SqlConnect();
con.SqlQuery("Select * from DeductionInfo where [IS Percentage] = #yes");
con.cmd.Parameters.AddWithValue("#yes", "' Yes '");
sdr = con.cmd.ExecuteReader();
if (sdr.Read().ToString() == "Yes")
{
ii.SubItems[2].Text = string.Format("{0:C}", Convert.ToDouble(ii.SubItems[2].Text.ToString()));
}
else
{
ii.SubItems[2].Text = string.Format("{0:P0}", Convert.ToDouble(ii.SubItems[2].Text.ToString()));
}
con.cmd.Connection.Close();
But the output is not what I want:
I want the values to be formatted to Dollar sign if the condition is "No" and Percent if the conditions is "Yes". Can I have a help on this? Thanks
Here is the answer to my own question. I took it out inside the foreach loop and made a for loop.
con = new SqlConnect();
con.SqlQuery("Select * from DeductionInfo order by [Deduction Title] ASC");
sda = new SqlDataAdapter(con.cmd);
ds = new DataSet();
sda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i].ItemArray[3].ToString() == "Yes")
{
lvUserManagement.Items[i].SubItems[2].Text = string.Format("{0:P0}", Convert.ToDouble(lvUserManagement.Items[i].SubItems[2].Text.ToString()));
}
else if (ds.Tables[0].Rows[i].ItemArray[3].ToString() == "No")
{
lvUserManagement.Items[i].SubItems[2].Text = string.Format("{0:C}", Convert.ToDouble(lvUserManagement.Items[i].SubItems[2].Text.ToString()));
}
}
con.cmd.Connection.Close();
enter image description here
I have an attendancesheet program. I have triple checked my database tables and all of their columns are null. I said if they are not null go through but although all of them are null it goes through them all :D I don't know whats wrong.
private void textBoxX1_KeyDown(object sender, KeyEventArgs e)
{
sqlcon.Close();
sqlcon.Open();
if (e.KeyCode == Keys.Enter)
{
string t = lbl_Time.Text;
string d = lbl_Date.Text;
string selectQueryName = "SELECT name FROM tbl_attendanceMembers where memberCode=" + "'" + textBoxX1.Text + "'";
var sqlcmdName = new SqlCommand(selectQueryName, sqlcon);
var resultName = sqlcmdName.ExecuteScalar();
string selectQueryId = "SELECT MAX(id) FROM tbl_attendanceSheet";
var sqlcmdId = new SqlCommand(selectQueryId, sqlcon);
var resultId = sqlcmdId.ExecuteScalar();
(1)if (resultId != null)
{
string selectQueryCockin = "SELECT Clockin FROM tbl_attendanceSheet where id=" + "resultId";
var sqlcmdCockin = new SqlCommand(selectQueryCockin, sqlcon);
var resultCockin = sqlcmdId.ExecuteScalar();
(2)if (resultCockin != null)
{
(3)if (resultName != null)
{
this.lbl_mmbrname.Text = resultName.ToString();
this.lbl_timestored.Text = t;
textBoxX1.Clear();
}
}
}
else //if result id == null
{
sqlcon.Open();
SqlCommand sqlcmdClockin = new SqlCommand("InputClockIn", sqlcon);
sqlcmdClockin.CommandType = CommandType.StoredProcedure;
sqlcmdClockin.Parameters.AddWithValue("#InputDate", d);
sqlcmdClockin.Parameters.AddWithValue("#InputTime", t);
sqlcmdClockin.ExecuteNonQuery();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT * FROM tbl_attendanceMembers", sqlcon);
DataTable dt = new DataTable();
sqlda.Fill(dt);
dataGridView1.DataSource = dt;
}
sqlcon.Close();
}
}
When I execute this code, it equals lbl_mmbrname.Text to resultName and lbl_timestored.Text = t. So it means it has gone through all the way down into the 3rd if statement which is false...
I have checked it via break poits(f9).
By the first sqlcon.close(); is because if I dont write it it will say connection is not closed which doesn't make sense to me because I have written a sqlcon.close(); down there...
According to this if on a DbCommand.ExecuteScalar()the database returns null your query gets a DbNull.Value object returned.
So I guess you need to check for that instead of null
EDIT
Relevant remark there:
If the first column of the first row in the result set is not found, a null reference is returned. If the value in the database is null, the query returns DBNull.Value.
so it can return both a null and DBNull.Value
I need to update the DB based on the fields in excel, but i need to check if 5 fields in a row in one column are empty, then stop updating the DB.
foreach (var sheets in workbook.Worksheets)
{
SqlCommand comm = new SqlCommand(query, conn);
comm.CommandType = System.Data.CommandType.Text;
var start = sheets.Dimension.Start;
var end = sheets.Dimension.End;
for (int i = start.Row + 1; i < end.Row; i++)
{
object columnE = sheets.Cells[i, 4].Value;
string aa = columnE.ToString();
if (aa.StartsWith("E") && aa.EndsWith("ETO"))
{
comm.Parameters.AddWithValue("#columnE", columnE);
object columnB = sheets.Cells[i, 1].Value;
comm.Parameters.AddWithValue("#columnB", columnB);
}
else if (string.IsNullOrEmpty(aa) || !aa.StartsWith("E") && !aa.EndsWith("ETO"))
{
conn.Close();
}
comm.ExecuteNonQuery();
comm.Parameters.Clear();
}
}
I have a logic when the first fields is null or empty or not what is intended to be to stop updating, but i can't find a way to check that for 5 fields in a row.
I have found the solution, here it is for the future people.
foreach (var sheets in workbook.Worksheets)
{
conn.Open();
result = sheets.ToString();
SqlCommand comm = new SqlCommand(query, conn);
comm.CommandType = System.Data.CommandType.Text;
var start = sheets.Dimension.Start;
var end = sheets.Dimension.End;
int counter = 0;
for (int i = start.Row + 1; i < end.Row; i++)
{
object columnE = sheets.Cells[i, 5].Value;
string aa = "";
if (columnE != null)
{
aa = columnE.ToString();
}
object columnB = sheets.Cells[i, 2].Value;
if (aa.StartsWith("E") && aa.EndsWith("ETO") && conn.State == System.Data.ConnectionState.Open)
{
comm.Parameters.AddWithValue("#columnE", columnE);
comm.Parameters.AddWithValue("#columnB", columnB);
comm.ExecuteNonQuery();
comm.Parameters.Clear();
}
if (columnE == null)
{
counter++;
}
if (counter == 5)
{
conn.Close();
}
}
}
Just count to 5 where you have true logic otherwise reset the counter to start over.
Int counter =0;
for (){
If (logictrue()){
counter++;
if(counter==5)
Update();
} else
counter=0;
}
I'm trying to implement date-picker functionality in my project, but I can't do it quite right. I'm trying to pass the date-picker value in my oracle string so that it will compare with my db column and return results on the date criteria...
Whenever I pass it to the select statement it won't generate errors particularly but on button click it doesn't perform anything except it shows "not connected".
str = "Select * from sania.doctor where APPOINTMENT_DATE = "+ datepicker1.value;
It is clear it is logical mistake but I'm new to this C# concepts I need someone to tell me how to pass it and then display the results as well.
private void button1_Click(object sender, EventArgs e)
try
{
OracleCommand com;
OracleDataAdapter oda;
string ConString = "Data Source=XE;User Id=system;Password=sania;";
OracleConnection con = new OracleConnection(ConString);
{
// string id = dateTimePicker1.Text.Trim();
con.Open();
// str = "Select * from sania.doctor where APPOINTMENT_DATE = " + dateTimePicker1.value;
str = "select * from sania.doctor where APPOINTMENT_DATE to_date('"+dateTimePicker1.Value.ToString("yyyyMMdd") + "', 'yyyymmdd')";
com = new OracleCommand(str);
oda = new OracleDataAdapter(com.CommandText, con);
dt = new DataTable();
oda.Fill(dt);
Rowcount = dt.Rows.Count;
//int val = 0;
for (int i = 0; i < Rowcount; i++)
{
dt.Rows[i]["APPOINTMENT_DATE"].ToString();
//if (id == dateTimePicker1.Value)// this LINE SHOWS ERROR--because it is a string and I am using date with it. Don't know conversion
// {
// val = 1;
//}
}
// if (val == 0)
// { MessageBox.Show("INVALID ID"); }
// else
// {
DataSet ds = new DataSet();
oda.Fill(ds);
if (ds.Tables.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
else { MessageBox.Show("NO RECORDS FOUND"); }
}
}
//}
catch (Exception)
{ MessageBox.Show("not connected"); }
}
Do not put values into SQL directly, use bind variables/parametes instead. For Oracle:
// :prm_Appointment_Date bind variable declared within the query
String str =
#"select *
from sania.doctor
where Appointment_Date = :prm_Appointment_Date";
....
using(OracleCommand q = new OracleCommand(MyConnection)) {
q.CommandText = str;
// datepicker1.Value passed into :prm_Appointment_Date via parameter
q.Parameters.Add(":prm_Appointment_Date", datepicker1.Value);
...
}
Doing like that you can be safe from either SQL Injection or Format/Culture differences
I've created a program to mine and import data from about 75 spreadsheets into an oracle table. I'm able to connect, iterate through sheets, and grab cells and rows seemingly fine. The problem is if the excel sheet was saved with grouped rows collapsed, it skips the rows.
I can't find anywhere if there is an extended property or reg setting to allow me to possibly expand the groups on entry? Not sure how to getting around a collapsed group (not merged cell , those I can process without a problem).
code bits :
//Starting where I iterate through a particular sheet
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; data source={0}; Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1;ReadOnly=0\"", fileName);
OleDbConnection objConn = new OleDbConnection(connectionString);
try
{
objConn.Open();
System.Data.DataTable dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
if (dt != null)
{
foreach (DataRow row in dt.Rows)
{
var adapter = new OleDbDataAdapter("SELECT F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12 FROM [" + row["TABLE_NAME"].ToString() + "]", connectionString);
var ds = new DataSet();
try
{
adapter.Fill(ds, "anyname");
}
catch
{
break;
}
DataTable data = ds.Tables[0];
int rownum = 0;
// <a bunch of variable declarations>
foreach (DataRow row_b in data.Rows)
{
// start slogging through the rows
rownum = rownum++;
// <reset some variables>
if (rownum == 1) // Catch valid scripts that contain a number
{
foreach (DataColumn column in data.Columns)
{
if (column.ToString() == "F1")
{
// <processing code for this column>
}
if (column.ToString() == "F2")
{
// <processing code for this column>
}
if (column.ToString() == "F3")
{
// <you get the picture>
}
}
}
if (rownum == 3)
{
// <moving along through the rows...different processing>
}
// <..rows 4-11..>
if (rownum > 12 )
{
// <more value assignment>
}
string allvals = APPLICATION + E_USER + STEP_DESC + VARIATIONS + STATUS + STOPS_TESTING + ISSUE_NUM + ISSUE_COMMENTS + ADDITIONAL_INFO;
allvals = allvals.Trim();
//Don't want sheets that come across as Print Area this shouldn't affect the row processing
isPrintArea = 0;
if (BOOKSHEET.Contains("Print_Area"))
{
isPrintArea = 1;
}
Boolean addornot=false;
if (cb_forallscripts.Checked == true)
{
addornot = (STEP_NUM != 0 &&
allvals != "" &&
isPrintArea == 0 &&
SCRIPT_NUM != 0);
}
else
{
addornot = (STEP_NUM != 0 &&
allvals != "" &&
isPrintArea == 0 &&
SCRIPT_NUM != 0 &&
runScripts.Contains(SCRIPT_NUM.ToString()));
}
if (addornot)
{
//<connect to our Oracle db, I set up oCmd outside this>
OracleCommand oCmd = new OracleCommand();
oCmd.Connection = oConn;
oCmd.CommandType = CommandType.Text;
oCmd.Parameters.Add("STEP_NUM", STEP_NUM);
// <... bunch of parameters ...>
oCmd.Parameters.Add("script", SCRIPT);
oCmd.CommandText = "<My insert statement> ";
oCmd.ExecuteNonQuery();
}
}
}
}
}
catch ( <error processing>)
{ }
Rows.OutlineLevel should be the VBA property you are looking for. It can be read or set. See this page for Microsoft's rather terse description. Range.ClearOutline will, as it says, clear the outline for a specified range, as explained here.