How to ignore the empty cell in the GridView - c#

I have a GridView and Edit link for each row. I can click on Edit and fill data in the cells of GridView and can Update the GridView row and the corresponding table in the database is also updated.
I have a save button, which on_click reads each and every row, column by column and perform some action.
The function works fine if all the cell in the GridView has some data filled in it. If the cell in the GridView is empty, it gives and error : Input String is not in the correct format.
The code I have tried is :
protected void SAVE_GRID_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView2.Rows)
{
string Loc = row.Cells[1].Text;
string strg = "SELECT Location_Type FROM Quantity WHERE Locations='" + Loc + "'";
SqlCommand com = new SqlCommand(strg, con);
con.Open();
SqlDataReader sdr = com.ExecuteReader();
while (sdr.Read())
{
Loctype.Text = sdr[0].ToString().Trim();
}
con.Close();
for (int i = 1; i < GridView2.Columns.Count; i++)
{
String header = GridView2.Columns[i].HeaderText;
string str = "SELECT Profile_Type FROM Profile_Tooltip WHERE Profile_Name='"+header+"'";
SqlCommand cmd = new SqlCommand(str,con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
profiletype.Text = dr[0].ToString().Trim();
}
con.Close();
if (!string.IsNullOrEmpty(row.Cells[i + 1].Text.Trim()))
{
int n = Convert.ToInt16(row.Cells[i + 1].Text);
//int n = int.Parse(row.Cells[i].Text);
for (int m = Asset_List.Items.Count - 1; m >= 0; m--)
{
Asset_List.Items.Remove(Asset_List.Items[m]);
}
for (int j = 1; j <= n; j++)
{
Asset_List.Items.Add(string.Concat(profiletype.Text, j));
}
for (int k = 0; k <= Asset_List.Items.Count - 1; k++)
{
com = new SqlCommand("INSERT INTO " + Label3.Text + " VALUES ('" + Loctype.Text + "','" + Loc + "','" + header + "','" + Asset_List.Items[k] + "')", con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
}
}
}
SqlCommand comd = new SqlCommand("SELECT * FROM " + Label3.Text + "", con);
SqlDataAdapter da = new SqlDataAdapter(comd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
I want to check if the cell is empty, if empty I want to increment to next cell without performing any action for the empty cell.
Kindly help me solve this problem. Thank you.

just use trim and sting function
if (!string.IsNullOrEmpty(row.Cells[i].Text.Trim() ) )
you need to check here
int n = Convert.ToInt16(row.Cells[i + 1].Text);
check the string is convertible to integer or not using parse or tryparse methods of framework
short n = 0;
if(Int16.TryParse(row.Cells[i + 1].Text,out n);)
{
//perform function and user n here now
}

The line that sticks out the most to me is this one:
int n = Convert.ToInt16(row.Cells[i + 1].Text);
I usually use something like this to avoid exceptions:
int n = 0;
bool didParse = Int16.TryParse(row.Cells[i + 1].Text, out n);
if (didParse)
{
//add code here
}
Your error might be an exception being thrown because your cell text is empty or perhaps even null.

Related

Data gets duplicated in datagridview when query applied?

I am trying to perform CRUD operation on winform
This is for ASP.NET winform in which whenever I try to insert, update or delete the data to or from the database first of all rows and inside content gets duplicated
https://imgur.com/a/d5jgv6H
however, upon restarting the application data shows up correctly
private void button2_Click(object sender, EventArgs e)
{
//insert
try
{
con.Open();
//.text property gets/Sets text associated with this control
String name = textBox1.Text.ToString();
String address = textBox2.Text.ToString();
String number = textBox3.Text.ToString();
long pnumber = Int64.Parse(number);
String sem = textBox4.Text.ToString();
long semester = Int64.Parse(sem);
string branch = comboBox1.SelectedItem.ToString();
String query = "insert into student values('" + name + "','" + address + "'," + pnumber + "," + semester + ",'" + branch + "')";
SqlCommand sqlcom = new SqlCommand(query, con);
int i = sqlcom.ExecuteNonQuery();
if (i >= 1)
{
MessageBox.Show("Student has been Registered: " + name);
}
else
{
MessageBox.Show("Registration Failed ! ");
}
//clearing data
button1_Click(sender, e);
show();
con.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error is : " + exp.ToString());
}
}
void show()
{
String query = "select * from student";
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dataInTable = new DataTable();
adapter.Fill(dataInTable);
//DataRow represents row of data in DataTable
foreach (DataRow item in dataInTable.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[n].Cells[4].Value = item[4].ToString();
}
}
The query works fine but rows still get duplicated. What's the problem?
I can't find any bug, so I assume I am doing something incorrectly.
Your show method adds rows to the grid, but it never removes the rows which are already in the grid.
Normally one would use data binding to populate a DataGridView or other data-bound controls. I'm going to assume you have reasons for just adding rows directly (perhaps it's simpler for your needs) and not change that. Given that structure, probably the easiest thing to do is just to clear the grid before adding the new rows:
void show()
{
String query = "select * from student";
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dataInTable = new DataTable();
adapter.Fill(dataInTable);
dataGridView1.Rows.Clear(); // <--- here
foreach (DataRow item in dataInTable.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[n].Cells[4].Value = item[4].ToString();
}
}
That way any time you are about to populate the grid with new data, you first clear the existing data from it.

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

Handling 'NULL' and key constraints when inserting data from a gridview

I'm trying to insert values into the database via gridview from a C# Windows application. I tried 2 different methods but neither seems to be working for me. The 2 type of code is shown below......
Assuming, even if the code below works.... I'm getting various errors regarding the primary key and foreign key constraints.......
Problem:
I have confactorID and macroID columns as integer with nullable in destination businesslogic table....... I'm not sure how to insert 'NULL' in these columns from the C# gridview tool...
Even if I give integer values as input there seems to be foreign key and primary key (duplication) constraint issues....
What do I need to change in my below code to resolve these issues.... I've been stuck with these problem for more than 8 hours... Any help is much appreciated.
Code type 1:
private void ADD_button_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(sqlconn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
con.Open();
for (int i = 1; i < dataGridView.Rows.Count; i++)
{
string sql = #"INSERT INTO " + schemaName +"ERSBusinessLogic VALUES ("
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_ID"].Value + ", '"
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_Formula"].Value.ToString() + "', "
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsCount"].Value + ",'"
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_Inputs"].Value.ToString() + "', "
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value + ", "
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value + ", '"
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_DataSeries"].Value.ToString() + "', '"
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_InputTimeDimensionValue"].Value.ToString() + "', "
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_InputTimeDimensionType"].Value + ", "
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_GeographyDimensionID"].Value + ", "
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsUnitsIDs"].Value + ", '"
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_Type"].Value + "', "
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_PrivacyID"].Value + ", '"
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_LongDesc"].Value.ToString() + "', '"
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_InputSources"].Value.ToString() + "', '"
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputName"].Value.ToString() + "', "
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputUnitID"].Value + ", '"
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputDestination"].Value.ToString() + "', '"
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputTimeDimensionValue"].Value.ToString() + "', "
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputTimeDimensionType"].Value + ", "
+ dataGridView.Rows[i].Cells["ERSBusinessLogic_GroupID"].Value + ");";
if ((dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value == " ") && (dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value == null))
{
Convert.ToInt32(dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value = "NULL");
Convert.ToInt32 (dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value = "NULL");
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
else
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
finally
{
con.Close();
}
}
Code type 2:
private void ADD_button_Click(object sender, EventArgs e)
{
// Getting data from DataGridView
DataTable myDt = new DataTable();
myDt = GetDTfromDGV(dataGridView);
// Writing to sql
WriteToSQL(myDt);
}
private DataTable GetDTfromDGV(DataGridView dgv)
{
// Making our DataTable
DataTable dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns)
{
dt.Columns.Add(column.Name, typeof(string));
}
// Getting data
foreach (DataGridViewRow dgvRow in dgv.Rows)
{
DataRow dr = dt.NewRow();
for (int col = 0; col < dgv.Columns.Count; col++)
{
dr[col] = dgvRow.Cells[col].Value;
}
dt.Rows.Add(dr);
}
// removing empty rows
for (int row = dt.Rows.Count - 1; row >= 0; row--)
{
bool flag = true;
for (int col = 0; col < dt.Columns.Count; col++)
{
if (dt.Rows[row][col] != DBNull.Value)
{
flag = false;
break;
}
}
if (flag == true)
{
dt.Rows.RemoveAt(row);
}
}
return dt;
}
private void WriteToSQL(DataTable dt)
{
using (SqlConnection con = new SqlConnection(sqlconn))
{
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con);
// Setting the database table name
sqlBulkCopy.DestinationTableName = "[AnimalProductsCoSD].[CoSD].[ERSBusinessLogic]";
// Mapping the DataTable columns with that of the database table
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[0].ColumnName, "ERSBusinessLogic_ID"));
Convert.ToString(sqlBulkCopy.ColumnMappings.Add(dt.Columns[1].ColumnName, "ERSBusinessLogic_Formula"));
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[2].ColumnName, "ERSBusinessLogic_InputsCount"));
Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[3].ColumnName, "ERSBusinessLogic_Inputs"));
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[4].ColumnName, "ERSBusinessLogic_ConvFactorID"));
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[5].ColumnName, "ERSBusinessLogic_MacroID"));
Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[6].ColumnName, "ERSBusinessLogic_DataSeries"));
Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[7].ColumnName, "ERSBusinessLogic_InputTimeDimensionValue"));
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[8].ColumnName, "ERSBusinessLogic_InputTimeDimensionType"));
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[9].ColumnName, "ERSBusinessLogic_GeographyDimensionID"));
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[10].ColumnName, "ERSBusinessLogic_InputsUnitsIDs"));
Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[11].ColumnName, "ERSBusinessLogic_Type"));
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[12].ColumnName, "ERSBusinessLogic_PrivacyID"));
Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[13].ColumnName, "ERSBusinessLogic_LongDesc"));
Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[14].ColumnName, "ERSBusinessLogic_InputSources"));
Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[15].ColumnName, "ERSBusinessLogic_OutputName"));
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[16].ColumnName, "ERSBusinessLogic_OutputUnitID"));
Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[17].ColumnName, "ERSBusinessLogic_OutputDestination"));
Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[18].ColumnName, "ERSBusinessLogic_OutputTimeDimensionValue"));
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[19].ColumnName, "ERSBusinessLogic_OutputTimeDimensionType"));
Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[20].ColumnName, "ERSBusinessLogic_GroupID"));
con.Open();
sqlBulkCopy.WriteToServer(dt);
}
}
Thanks
First of all check your database table, columns that keeps IDs from another tables must allow null value like so:
And if your table ID is Identity column with auto increment you don't need to write ID, table automatically add ID.
If everything ok then try to do like so:
private DataTable GetDTfromDGV(DataGridView dgv)
{
// Macking our DataTable
DataTable dt = new DataTable();
//Another way to add columns
dt.Columns.AddRange(new DataColumn[5]
{
//new DataColumn("table_ID", typeof(string)), if table_ID is not Identity column with auto increment then uncomment
new DataColumn("sql_col2", typeof(string)),
new DataColumn("sql_col3", typeof(string)),
new DataColumn("sql_col4", typeof(string)),
new DataColumn("Table_2_ID", typeof(int)),
new DataColumn("Table_3_IDt", typeof(int))
});
// Getting data
foreach (DataGridViewRow dgvRow in dgv.Rows)
{
DataRow dr = dt.NewRow();
for (int col = 1; col < dgv.Columns.Count; col++) //if table_ID is not Identity column with auto increment then start with 0
{
dr[col - 1] = dgvRow.Cells[col].Value == null ? DBNull.Value : dgvRow.Cells[col].Value;
}
dt.Rows.Add(dr);
}
// removing empty rows
....
return dt;
}
private void WriteToSQL(DataTable dt)
{
string connectionStringSQL = "Your connection string";
using (SqlConnection sqlConn = new SqlConnection(connectionStringSQL))
{
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConn);
// Setting the database table name
sqlBulkCopy.DestinationTableName = "Table_1";
// Mapping the DataTable columns with that of the database table
//sqlBulkCopy.ColumnMappings.Add(dt.Columns[0].ColumnName, "table_ID"); table_ID is Identity column with auto increment
sqlBulkCopy.ColumnMappings.Add(dt.Columns[0].ColumnName, "sql_col2");
sqlBulkCopy.ColumnMappings.Add(dt.Columns[1].ColumnName, "sql_col3");
sqlBulkCopy.ColumnMappings.Add(dt.Columns[2].ColumnName, "sql_col4");
sqlBulkCopy.ColumnMappings.Add(dt.Columns[3].ColumnName, "Table_2_ID");
sqlBulkCopy.ColumnMappings.Add(dt.Columns[4].ColumnName, "Table_3_ID");
sqlConn.Open();
sqlBulkCopy.WriteToServer(dt);
}
}
I tried and that's what I got:
You could use parameterized query.
For example:
var sqlcommand = new SqlCommand
{
CommandText = "INSERT INTO TABLE(Column1,Column2) VALUES(#Column1Value,#Column2Value)"
};
var param1 = new SqlParameter("#Column1Value", SqlDbType.Int)
{
Value = (String.IsNullOrWhiteSpace(dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value)) ? DBNull.Value: (object)(dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value)
};
var param2 = new SqlParameter("#Column2Value", SqlDbType.Int)
{
Value = (String.IsNullOrWhiteSpace(dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value)) ? DBNull.Value : (object)dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value)
};
sqlcommand.Parameters.Add(param1);
sqlcommand.Parameters.Add(param2);
If you use method 1 that you tried, you'll probably want to create SqlParameter objects and parameterize your query. Refer to this SO post: Right syntax of SqlParameter. That being said, you just want to get it to work first I'm sure. You could check the value of the DataGridViewCell's Value property for the convFactorID and macroID. If either of these are null, then you can assign a string the text "NULL". For brevity, I've used the C# conditional operator (https://msdn.microsoft.com/en-us/library/ty67wk28.aspx). This is one way you might do what I'm describing:
string convFactorIDText = (dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value == null) ? "NULL" : dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value.ToString();
string macroIDText = (dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value == null) ? "NULL" : dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value.ToString();
Then alter you SQL to include the string variables that contain either a actual value or NULL.
string sql = string.Format(#"INSERT INTO {0}.ERSBusinessLogic VALUES ({1}, '{2}', {3}, {4}, {5}, {6}"),
schemaName,
dataGridView.Rows[i].Cells["ERSBusinessLogic_ID"].Value,
dataGridView.Rows[i].Cells["ERSBusinessLogic_Formula"].Value.ToString(),
dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsCount"].Value,
dataGridView.Rows[i].Cells["ERSBusinessLogic_Inputs"].Value,
convFactorIDText,
macroIDText
// and so forth
);

Using DataTable.update() does not add entries to my SQL Server database in one method but does in another

I have a method (AddRowToSQLTable()) that is passed a row, it then creates a row array containing that row and then passes it to DataTable.update().
This works fine. The SQL Server is updated and the next time I run (debug) the program the new data is present.
Another method (AddStock()) uses a similar structure but does not work.
The difference being that I am passing a data table in Update() not a Row[] however no exception is thrown just nothing is updated/added on the server.
Can someone please explain what exactly is going on and why these differ? I would like to know this even if the solution is to use a different structure to achieve what I want so I know for the future and have a better understanding.
To Note:
I have tested to ensure the DataTable being passed contains records. The DataTable is of the same format as the target SQL Server table.
I have also tried SqlBulkCopy and encounter the same problem.
Many thanks!
private DataTable StockAdditions;
public void PrepareStockQuantitiesForAdding()
{
if (StockAdditions != null)
{
StockAdditions.Clear();
}
StockAdditions = StockQuantitiesTable.Clone();
int Count = 0;
DataRow RowToAdd = StockQuantitiesTable.NewRow();
DataView AreaIDs = new DataView(AreaTable);
DataView Conditions = new DataView(ConditionsTable);
int AreaID;
string ConditionCode;
foreach (DataRow Row in SessionSKUScanned.Rows)
{
if (Row["Serial Number"].ToString() == "")
{
Conditions.RowFilter = "([Name] = '" + Row["Condition"] + "')";
ConditionCode = Conditions[0][2].ToString();
AreaIDs.RowFilter = "([StorageAreaName] = '" + Row["Area"] + "')";
AreaID = Convert.ToInt32(AreaIDs[0][0]);
DataView StockQuantities = new DataView(StockQuantitiesTable);
StockQuantities.RowFilter = "([QuantityID] = '" + AreaID + "-" + Row["SKU"] + "-" + ConditionCode + "')";
if (StockQuantities.Count > 0)
{
StockQuantities[0][3] = Convert.ToInt32(StockQuantities[0][3]) + 1;
RowToAdd["QuantityID"] = AreaID + "-" + Row["SKU"] + "-" + ConditionCode;
RowToAdd["SKU"] = Row["SKU"];
RowToAdd["AreaID"] = AreaID;
RowToAdd["Quantity"] = StockQuantities[0][3] = Convert.ToInt32(StockQuantities[0][3]) + 1;
RowToAdd["Condition"] = Row["Condition"];
}
else
{
RowToAdd["QuantityID"] = AreaID + "-" + Row["SKU"] + "-" + ConditionCode;
RowToAdd["SKU"] = Row["SKU"];
RowToAdd["AreaID"] = AreaID;
RowToAdd["Quantity"] = 1;
RowToAdd["Condition"] = Row["Condition"];
}
Count++;
}
else
{
RowToAdd["QuantityID"] = Row["Serial Number"];
RowToAdd["SKU"] = Row["SKU"];
AreaIDs.RowFilter = "([StorageAreaName] = '" + Row["Area"] + "')";
RowToAdd["AreaID"] = Convert.ToInt32(AreaIDs[0][0]);
RowToAdd["Quantity"] = 1;
RowToAdd["Condition"] = Row["Condition"];
Count++;
}
StockQuantitiesTable.ImportRow(RowToAdd);
MessageBox.Show(RowToAdd[0].ToString());
StockAdditions.ImportRow(RowToAdd);
}
}
private void AddRowToSQLTable(DataRow Row, string SQLTableName)
{
DataRow[] Rows = new DataRow[1];
Rows[0] = Row;
SqlConnection SQLConn = new SqlConnection(ConfigurationManager.ConnectionStrings["eCommStock.Properties.Settings.Demo_SiteConnectionString"].ConnectionString);
SQLConn.Open();
SqlDataAdapter daUpdateTable = new SqlDataAdapter("Select * From " + SQLTableName, SQLConn);
SqlCommandBuilder SQLcmdBuilder = new SqlCommandBuilder(daUpdateTable);
daUpdateTable.Update(Rows);
SQLConn.Close();
}
public void AddStock()
{
SqlConnection SQLConn = new SqlConnection(ConfigurationManager.ConnectionStrings["eCommStock.Properties.Settings.Demo_SiteConnectionString"].ConnectionString);
SQLConn.Open();
SqlDataAdapter daUpdateTable = new SqlDataAdapter("Select * From StockQuantities", SQLConn);
SqlCommandBuilder SQLcmdBuilder = new SqlCommandBuilder(daUpdateTable);
daUpdateTable.Update(StockAdditions);
SQLConn.Close();
}
It doesn't work because RowToAdd.RowState is Detached. I don't like it, but the following is a quick and dirty solution, before importing the row to StockAdditions, make sure the row is in Added state, later you can "detach" the row again.
StockQuantitiesTable.Rows.Add(RowToAdd);
StockAdditions.ImportRow(RowToAdd);
StockQuantitiesTable.Rows.Remove(RowToAdd);

Taking Value from Database and Create XML FILE VIA C#

Well I produce code which takes the values from the database and creates XML files, but I stack on how to modify my code in order to avoid the empty cells from the column VALUES, also I need to select the data from the column VALUES where the column SELECT is 1. Can you please help me with examples? Thank you in advance .
code
public DataSet produceFieldsXml(int langID, int presID)
{
SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["beta"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter(#"SELECT IsubField.ID,IsubField.SUBJECT_ID as SUBJECTID,IsubField.VALUE AS DSCR,IsubField.FIELD_TYPE_ID, PFTT.VALUE AS TITLE
FROM I_SUBJECT_FIELD IsubField, P_FIELD_TYPE_TITLE PFTT
WHERE IsubField.PRESENTATION_ID = " + presID + #"
AND IsubField.LANGUAGE_ID = " + langID + #"
AND PFTT.FIELD_TYPE_ID = IsubField.FIELD_TYPE_ID
AND PFTT.LANGUAGE_ID = " + langID + #"
ORDER BY IsubField.SUBJECT_ID", con);
DataSet ds = new DataSet();
da.Fill(ds, "FieldItem");
ds.Tables[0].Columns.Add("SEQ", typeof(Int64));
DataSet dsNew = new DataSet();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlDataAdapter daII = new SqlDataAdapter(#"SELECT CATEGORY_ID FROM I_SUBJECT WHERE ID = " + Convert.ToInt32(ds.Tables[0].Rows[i]["SUBJECTID"].ToString().Trim()) + "", con);
DataSet dsa = new DataSet();
daII.Fill(dsa, "FieldItem");
dsNew.Merge(dsa);
}
DataSet dsaa = new DataSet();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlDataAdapter daII = new SqlDataAdapter(#"SELECT SEQ FROM P_CATEGORY_FIELD WHERE CATEGORY_ID = " + Convert.ToInt32(dsNew.Tables[0].Rows[i]["CATEGORY_ID"].ToString().Trim()) + " AND FIELD_ID = " + Convert.ToInt32(ds.Tables[0].Rows[i]["FIELD_TYPE_ID"].ToString().Trim()) + "", con);
daII.Fill(dsaa, "FieldItem");
ds.Tables[0].Rows[i]["SEQ"] = dsaa.Tables[0].Rows[0]["SEQ"];
}
for (int i = 0; i > dsaa.Tables[0].Rows.Count; i++)
{
ds.Tables[0].Rows[i]["SEQ"] = dsaa.Tables[0].Rows[0]["SEQ"];
}
dsaa.WriteXml(Server.MapPath("~/") + "ZipFiles\\" + "new.xml");
return ds;
}
If I were you I'd really try to learn more SQL, because I'm pretty sure those three queries above can be one query given the right joins. Unfortunately we cannot help you right now, unless you show us what I_SUBJECT_FIELD, P_FIELD_TYPE_TITLE, I_SUBJECT and P_CATEGORY_FIELD look like and how they're related.
Because this is simply very bad:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlDataAdapter daII = new SqlDataAdapter(#"SELECT CATEGORY_ID FROM I_SUBJECT WHERE ID = " + Convert.ToInt32(ds.Tables[0].Rows[i]["SUBJECTID"].ToString().Trim()) + "", con);
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlDataAdapter daII = new SqlDataAdapter(#"SELECT SEQ FROM P_CATEGORY_FIELD WHERE CATEGORY_ID = " + Convert.ToInt32(dsNew.Tables[0].Rows[i]["CATEGORY_ID"].ToString().Trim()) + " AND FIELD_ID = " + Convert.ToInt32(ds.Tables[0].Rows[i]["FIELD_TYPE_ID"].ToString().Trim()) + "", con);
}
Those queries get executed numerous times and at most they should be executed once (bit trickier in the second case, but not impossible), and in fact they really should be part of the main query (provided the tables are set up correctly).
An even bigger headscratcher is this:
for (int i = 0; i > dsaa.Tables[0].Rows.Count; i++)
{
ds.Tables[0].Rows[i]["SEQ"] = dsaa.Tables[0].Rows[0]["SEQ"];
}
...since that is exactly the same line as in the previous for-loop.
Once you manage to create a single query it will be far easier to convert that data into XML.
Also look into encapsulating code in using statements.

Categories

Resources