Excel empty fields - c#

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

Related

Filter Database values to set string format

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

Checkbox value stored and inserted multiple times

I have a program where i need to register questions. A question can have 1 or multiple right answers, as checked in the method checkTaskType().
All ints are declared in the start of the code.
Code runs fine and works, problem is that if i want to register multiple questions without closing the form, the value from previouse checkbox will be registered as a correct answer on the next question.
-- Dont mind DB design, thats a temporary solution
//Method for insert to DB
private void InsertQAData()
{
using (var con = new MySqlConnection(_connectionString))
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
#"INSERT INTO task(tasktext, alt_1, alt_2, alt_3, alt_4, alt_5, illustration_link, task_type, alt_1_correct, alt_2_correct, alt_3_correct, alt_4_correct, alt_5_correct)
VALUES (#taskText, #alt_1, #alt_2, #alt_3, #alt_4, #alt_5, #illustration_link, #taskType, #corrAlt1, #corrAlt2, #corrAlt3, #corrAlt4, #corrAlt5);";
cmd.Parameters.AddWithValue("#taskText", txtQuestion.Text);
cmd.Parameters.AddWithValue("#alt_1", txtAlt_1.Text);
cmd.Parameters.AddWithValue("#alt_2", txtAlt_2.Text);
cmd.Parameters.AddWithValue("#alt_3", txtAlt_3.Text);
cmd.Parameters.AddWithValue("#alt_4", txtAlt_4.Text);
cmd.Parameters.AddWithValue("#alt_5", txtAlt_5.Text);
cmd.Parameters.AddWithValue("#illustration_link", txtLink.Text);
cmd.Parameters.AddWithValue("#taskType", taskType);
cmd.Parameters.AddWithValue("#corrAlt1", corrAlt1);
cmd.Parameters.AddWithValue("#corrAlt2", corrAlt2);
cmd.Parameters.AddWithValue("#corrAlt3", corrAlt3);
cmd.Parameters.AddWithValue("#corrAlt4", corrAlt4);
cmd.Parameters.AddWithValue("#corrAlt5", corrAlt5);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
lblInserted.Show();
}
// Method for checking if a question has 1 or multiple answers
private void checkTaskType()
{
if (checkBox1.Checked)
{
count += 1;
corrAlt1 = 1;
}
if (checkBox2.Checked)
{
count += 1;
corrAlt2 = 1;
}
if (checkBox3.Checked)
{
count += 1;
corrAlt3 = 1;
}
if (checkBox4.Checked)
{
count += 1;
corrAlt4 = 1;
}
if (checkBox5.Checked)
{
count += 1;
corrAlt5 = 1;
}
if (count == 1)
{
taskType = "oneAlternative";
}
if (count > 1)
{
taskType = "multipleAlternatives";
}
}
After calling the checkTaskType() call a method ClearResult() like:
private void ClearResult()
{
count = 0;
corrAlt1 = 0;
corrAlt2 = 0;
corrAlt3 = 0;
corrAlt4 = 0;
corrAlt5 = 0;
taskType = string.Empty;
}
This will help you after a question filled and stored to DB, reInitalize the varibles to default state.
So
checkTaskType();
//fill DB with values
//...
ClearResult();

invalid attempt to read when no data is present to ListBox in asp.net c#

My question is about to - Invalid attempt to read when no data is present to ListBox in asp.net c# SqDataReader
My code is :
SqlConnection oConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["evaConn"].ConnectionString);
try
{
oConn.Open();
SqlCommand oCmd = new SqlCommand();
oCmd.Connection = oConn;
oCmd.CommandText = str;
SqlDataReader dr = oCmd.ExecuteReader();
lstLeft.DataTextField = "drname";
lstLeft.DataValueField = "drid";
lstLeft.DataSource = dr;
lstLeft.DataBind();
for (int j = 0; j < lstLeft.Items.Count; j++)
{
while (dr.Read())
{
if (dr["othermr"].ToString() == "1")
{
lstLeft.Items[j].Text = lstLeft.Items[j].Text + " (Assigned to - " + dr["mrname"].ToString() + ")";
}
}
}
dr.Close();
}
catch (Exception)
{
}
finally
{
oConn.Close();
oConn.Dispose();
}
Error comes invalid attempt to read when no data is present to List Box in
asp.net c# after binding the data to Listbox
This is not a good practice to use DataReader inside for-loop:
for (int j = 0; j < lstLeft.Items.Count; j++)
{
while (dr.Read())
{
if (dr["othermr"].ToString() == "1")
{
lstLeft.Items[j].Text = lstLeft.Items[j].Text + " (Assigned to - " + dr["mrname"].ToString() + ")";
}
}
}
Note that DataReader is running in one direction so that when it exits the while loop, it reached end of loaded data sequence, thus it can't be used to get value of non-existent record when advanced to next loop (and returns invalid attempt to read when no data is present).
The correct way is using a counter inside while loop & counts every time the data has been read until the last sequence:
var dr = oCmd.ExecuteReader();
int j = 0;
while (dr.Read())
{
if (dr["othermr"].ToString() == "1")
{
lstLeft.Items[j].Text = lstLeft.Items[j].Text + " (Assigned to - " + dr["mrname"].ToString() + ")";
}
if (j == lstLeft.Items.Count)
{
break;
}
j++; // counter
}
I recommend to use DataTable if you still want to use for loop:
var dr = oCmd.ExecuteReader();
var dt = new DataTable();
dt.Load(dr); // load data into DataTable instead
for (int j = 0; j < lstLeft.Items.Count; j++)
{
// adjust the row index number so that you can get proper values
if (dt.Rows[j]["othermr"].ToString() == "1")
{
lstLeft.Items[j].Text = lstLeft.Items[j].Text + " (Assigned to - " + dt.Rows[j]["mrname"].ToString() + ")";
}
}
Additionally, when binding data source to a server control from DataReader you should use DataTable (and you can reuse it with for-loop above):
// taken from /a/14089639
using (var oCmd = new SqlCommand(str, oConn))
{
var dap = new SqlDataAdapter(oCmd);
var dt = new DataTable();
dap.Fill(dt);
lstLeft.DataTextField = "drname";
lstLeft.DataValueField = "drid";
lstLeft.DataSource = dt;
lstLeft.DataBind();
}
Note that you don't need to use oCmd.ExecuteReader() twice if on the first stage you're already putting DataReader contents inside DataTable.
Reference:
How to fill listBox Control?
Shail,
To me, your Reader becomes empty (but not null) after you bind it with Listbox.
So, if you change you code like below, i hope it will work for you:
SqlConnection oConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["evaConn"].ConnectionString);
try
{
oConn.Open();
SqlCommand oCmd = new SqlCommand();
oCmd.Connection = oConn;
oCmd.CommandText = str;
SqlDataReader dr = oCmd.ExecuteReader();
lstLeft.DataTextField = "drname";
lstLeft.DataValueField = "drid";
lstLeft.DataSource = dr;
lstLeft.DataBind();
dr.Close();//Close dr here
dr = oCmd.ExecuteReader();//fill it again here
for (int j = 0; j < lstLeft.Items.Count; j++)
{
while (dr.Read())
{
if (dr["othermr"].ToString() == "1")
{
lstLeft.Items[j].Text = lstLeft.Items[j].Text + " (Assigned to - " + dr["mrname"].ToString() + ")";
}
}
}
dr.Close();
}
catch (Exception)
{
}
finally
{
oConn.Close();
oConn.Dispose();
}

Update columns of database from csv file. Csv file could contain variable number of columns

Need your help. I have to get csv file from user and update database columns according to that file.
For Example:
File has following fields:
Name | Description | Date
Another file has:
Name | Price
Please Guide me how i could do this in c# using sql 2008.
From checkboxes user can select columns which he wants to update.
else if (count == 4 && dataGridView1.ColumnCount - 1 == 4)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
int id = Convert.ToInt32(dataGridView1.Rows[i].Cells["Id"].Value);
ItemsC.UpdateDatacolumns(id, columnsList[1], dataGridView1.Rows[i].Cells[1].Value.ToString(), columnsList[2], dataGridView1.Rows[i].Cells[2].Value.ToString(), columnsList[3], dataGridView1.Rows[i].Cells[3].Value.ToString());
}
}
else if (count == 5 && dataGridView1.ColumnCount - 1 == 5)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
int id = Convert.ToInt32(dataGridView1.Rows[i].Cells["Id"].Value);
ItemsC.UpdateDatacolumns(id, columnsList[1], dataGridView1.Rows[i].Cells[1].Value.ToString(), columnsList[2], dataGridView1.Rows[i].Cells[2].Value.ToString(), columnsList[3], dataGridView1.Rows[i].Cells[3].Value.ToString(), columnsList[4], dataGridView1.Rows[i].Cells[4].Value.ToString());
}
}
In Backend Just Override Update Method:
public static bool UpdateDatacolumns(int id, string column, string value, string column2, string value2)
{
SqlConnection conn = database.getConnection();
string query = "update destinationItemTable set " + column + "= #value ," + column2+" =#value2 where Id=#id";
try
{
var p1 = new SqlParameter("#id", id);
var p2 = new SqlParameter("#value", value);
var p3 = new SqlParameter("#value2", value2);
var cmd = new SqlCommand { CommandText = query, CommandType = CommandType.Text };
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
cmd.Connection = conn;
conn.Open();
bool result = (cmd.ExecuteNonQuery() > 0);
cmd.Dispose();
return result;
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}

How to Eliminate Checking of Null Value Datatable in IF condition

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.

Categories

Resources