How to overcome from the error - c#

i m making add,edit delete module...For that i have the following code in the c#,
private void listOfCompany_Load(object sender, EventArgs e)
{
//MessageBox.Show(updID.ToString());
con.ConnectionString = #"PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany_1.mdb";
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string sql = "SELECT * From tblCompany_1 WHERE ID="+updID;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
da.Fill(ds);
// dataGridView1.DataSource = ds.Tables[0];
DataRow dr = ds.Tables[0].Rows.Count;
textBox1.Text = dr.ItemArray.GetValue(0).ToString();
textBox4.Text = dr.ItemArray.GetValue(2).ToString();
/* int t = ds.Tables[0].Columns.Count;
for (int i = 0; i < cnt; i++)
{
dataGridView1.Rows[i].Cells[0].Value = dr.ItemArray.GetValue(0).ToString();
dataGridView1.Rows[i].Cells[1].Value = dr.ItemArray.GetValue(1).ToString();
dataGridView1.Rows[i].Cells[2].Value = dr.ItemArray.GetValue(2).ToString();
}*/
}
when i debug the application, then on add,edit and delete button, it gives me error at the "DataRow dr = ds.Tables[0].Rows[0];" that "IndexOutOf RangeException was handled" and the error is "There is no row at position 0."...How should i overcome from this?

Well that suggests there's no record with that ID. You should check for that before going ahead and trying to use it. You can use ds.Tables[0].Rows.Count to find out how many rows were returned.
You should also start using parameterized queries instead of including values directly within the SQL statement you're building, in order to avoid SQL injection attacks. If the ID is an integer then it probably isn't a problem here, but generally parameterized SQL queries are the way forward.

How about:
DataRow dr;
for(int i = 0; i<ds.Tables.Count; i++){
for(int j = 0; j<ds.Tables[i].Rows.Count; j++){
dr = ds.Tables[i].Rows[j];
//Do something with dr.
}
}
Note: It is possibly "Length" in stead of "Count". Can't remember right now:p

Related

Access value in OleDbDataApter

Using OleDbDataAdapter SQL query to search for secific entry in access database.
OleDbDataAdapter adapter1 = new OleDbDataAdapter(#"SELECT Gallery_Number FROM Paintings WHERE Painting Number = '" + searchString + "'", myDB);
searchString = Convert.ToString( adapter);
searchString returns System.Data.OleDb.OleDbDataAdapter and not a Gallery number.
I would like to know how to get the value of this adapter and put it into a textbox.
First of all, I'd use a Scalar for this, since you only return a single value.
OleDbCommand command = new OleDbCommand(queryString, connection);
command.Connection.Open();
int galeryNumber = (int)command.ExecuteScalar();
But let's take a look at your code:
DataSet galNum = new DataSet();
oledbAdapter.Fill(galNum);
int galeryNumber = int.Parse(ds.Tables[0].Rows[0].ItemArray[0].ToString());
The best way to gain access to a OleDbDataAdapter is by converting the result set into a `DataSet. Then you can iterate through this set.
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
DataRow dr = ds.Tables[0].Rows[i]; //One result line in your set
//DataRow contains n columns
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
string someEntry = dr[i].ToString();
}
}

A chart element with the name 'John' already exists in the 'SeriesCollection'

I am following this post, to build a bar chart and show on my webpage. Below is the code i have done to accomplish it:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from ForChart";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet, "Query");
foreach (DataRow row in myDataSet.Tables["Query"].Rows)
{
string seriesName = row["SalesRep"].ToString();
Chart1.Series.Add(seriesName);
Chart1.Series[seriesName].ChartType = SeriesChartType.Line;
Chart1.Series[seriesName].BorderWidth = 2;
for (int colIndex = 1; colIndex < myDataSet.Tables["Query"].Columns.Count; colIndex++)
{
string columnName = myDataSet.Tables["Query"].Columns[colIndex].ColumnName;
string YVal = Convert.ToString(row[columnName]);
Chart1.Series[seriesName].Points.AddXY(columnName, YVal);
}
}
GridView1.DataSource = myDataSet;
GridView1.DataBind();
cmd.Connection.Close();
And my table is having the below data. Please check the snapshot
But when i run the code i am getting the below error. Please help me to resolve the issue:
A chart element with the name 'John' already exists in the 'SeriesCollection'.
I am not able to traverse the records thats why i am getting this error, but i don't know how to traverse through all the records.
Coding help would be very much appreciated. Thanks.
I'm assuming that Chart1.Series requires unique names, and thus this call will fail when you try to enter the same name multiple times:
Chart1.Series.Add(seriesName);
Ugh, that entire example on MSDN is filled with bad practices:
select *
no usings used with SqlConnection, SqlCommand,...
mixing UI code and DB code (they should be in separate classes)
Look at this example for a possible solution.

searching more than 1 array index values from database in one query

i am doing a search from database. user will enter string. this string will be converted into array then this array indexed values will be checked from table to find the match.
I am using loop to traverse array query execution is in that loop, it searches fine but if there was more than one index to search it shows the last index searched values.
i know know that's not a proper way to search.
how can i do this.
SqlConnection conOpen;
string[] arrayList;
protected void Page_Load(object sender, EventArgs e)
{
DataLayer datalayer = new DataLayer();
conOpen = datalayer.connectionOpen();
string myString = Request.QueryString["searchText"].ToString();
char[] separator = new char[] { ' ' };
arrayList = myString.Split(separator);
for (int i = 0; i <= arrayList.GetUpperBound(0); i++)
{
Response.Write(arrayList[i]);
string asd = arrayList[i];
String arrayQuery = "Select * from tbl_products where product_name LIKE '%" + #asd + "%'";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(arrayQuery, conOpen);
da.Fill(ds, "tbl_products");
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
I'm too clear on what your final result is supposed to be but I'm going to guess. I think what you are asking is that you want the query to search for every instance of the search items (seperated by a space) the users put in the input element and return ALL of these findings to your GridView. Ok. So I would suggest you loop to "build" your sql statement and then run the sql and bind the data AFTER the loop (not during).
One more important element is that you should most definitely parametrize these values since it's coming from user input in order to prevent SQL-Injection. Please forgive any typos (it is late).
DataLayer datalayer = new DataLayer();
conOpen = datalayer.connectionOpen();
string myString = Request.QueryString["searchText"].ToString();
char[] separator = new char[] { ' ' };
arrayList = myString.Split(separator);
StringBuilder arrayQuery = new StringBuilder();
SqlCommand myCommand = new SqlCommand();
for (int i = 0; i < arrayList.Length; i++)
{
if (i==0)
{
arrayQuery.Append("Select * from tbl_products where product_name LIKE #asd" + i);
} else{
arrayQuery.Append(" OR product_name LIKE #asd" + i );
}
myCommand.Parameters.AddWithValue("#asd" + i, "%" + arrayList[i] + "%");
}
myCommand.CommandText = arrayQuery.ToString();
myCommand.Connection = conOpen;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(myCommand);
da.Fill(ds, "tbl_products");
GridView1.DataSource = ds;
GridView1.DataBind();

Dataset to xml Null Values

I have the code below, where from 3 tables I take the data and write an xml.
I want write (when a record column has null value) the column on the xml with null value. For example if (Category_name == Null ) to write on the xml (Null) Right now the code skip the column and don’t even have this column on the xml.
string xmlFileData = "";
string[] tables = new string[] { "category", "company", "config" };
string query;
xmlFileData += "<MyXml>";
SqlConnection conn;
dbconnect obj;
obj = new dbconnect();//initailizing class object
for (int i = 0; i < tables.Length; i++)
{
string ifemptquery;
DataSet ds = new DataSet();
DataSet ds1 = new DataSet();
conn = obj.getConnection(); //calling connection function
ifemptquery = "SELECT * FROM " + tables[i] ";
SqlCommand cmd1 = new SqlCommand(ifemptquery, conn);
conn.Open();
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
conn.Close();
if (dt1.Rows.Count > 0)
{
query = "SELECT * FROM " + tables[i] ";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
conn.Dispose();
ds.DataSetName = tables[i];
string vartbname = tables[i];
string trimed_tbname = vartbname.Replace("_", "");
ds.Tables[0].TableName = trimed_tbname;
xmlFileData += ds.GetXml();
}
else
{
}
}
xmlFileData += "</MyXml>";
File.WriteAllText(Server.MapPath("~/xmlbackup/") + "Backup.xml", xmlFileData);
I have been searching the whole world for a solution of writing null fields to XML using DataSet.WriteXML(). The answer posted by Vlad is the one I also used in my project but I found that following works in a much more performance optimized way. I have created a function for your convenience. Change your dataset tables one after the other by calling the following function and replacing the tables.
private DataTable GetNullFilledDataTableForXML(DataTable dtSource)
{
// Create a target table with same structure as source and fields as strings
// We can change the column datatype as long as there is no data loaded
DataTable dtTarget = dtSource.Clone();
foreach (DataColumn col in dtTarget.Columns)
col.DataType = typeof(string);
// Start importing the source into target by ItemArray copying which
// is found to be reasonably fast for nulk operations. VS 2015 is reporting
// 500-525 milliseconds for loading 100,000 records x 10 columns
// after null conversion in every cell which may be usable in many
// circumstances.
// Machine config: i5 2nd Gen, 8 GB RAM, Windows 7 64bit, VS 2015 Update 1
int colCountInTarget = dtTarget.Columns.Count;
foreach (DataRow sourceRow in dtSource.Rows)
{
// Get a new row loaded with data from source row
DataRow targetRow = dtTarget.NewRow();
targetRow.ItemArray = sourceRow.ItemArray;
// Update DBNull.Values to empty string in the new (target) row
// We can safely assign empty string since the target table columns
// are all of string type
for (int ctr = 0; ctr < colCountInTarget; ctr++)
if (targetRow[ctr] == DBNull.Value)
targetRow[ctr] = String.Empty;
// Now add the null filled row to target datatable
dtTarget.Rows.Add(targetRow);
}
// Return the target datatable
return dtTarget;
}
Refer similar question here - dataSet.GetXml() doesn't return xml for null or blank columns
Apart from solutions mentioned there, you can also traverse through dataset and write XML using XmlTextWriter. This method is not recommended if you are dealing with huge data.

Update a datatable with a string array as values

I have a problem where I am trying to update a datatable's columns with values from a string array and then submit those updates to the database. I have debugged this, thinking there is an error, but no exception is thrown.
I have also set my adapater's select statement and connection so I can modify the data that is retuned when the event is fired initially.
Here is my code (the _updateParams string array contain the values I am trying to update the table and the database with).
DataSet ds = new DataSet("SearchedRecord");
using (OracleConnection oc = new OracleConnection(DBConnection))
{
try
{
oc.Open();
OracleDataAdapter adap = new OracleDataAdapter(#"SELECT * FROM NEW_DATABASE", oc);
adap.FillSchema(ds, SchemaType.Source, "NEW_DATABASE");
adap.Fill(ds, "NEW_DATABASE");
OracleCommandBuilder bld = new OracleCommandBuilder(adap);
DataTable dt = ds.Tables["NEW_DATABASE"];
dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"] };
int key = int.Parse(dt.Rows[0]["ID"].ToString());
DataRow dr;
dr = dt.Rows.Find(key);
dr.BeginEdit();
for (int i = 0; i < _updateParams.Length; i++)
{
dr[0] = i.ToString();
}
dr.EndEdit();
dr.AcceptChanges();
dt.AcceptChanges();
adap.Update(ds, "NEW_DATABASE");
adap.UpdateCommand = bld.GetUpdateCommand();
adap.UpdateCommand.ExecuteNonQuery();
adap.UpdateCommand.Transaction.Commit();
}catch (Exception x)
{
x.Message.ToString();
}
}
Well, first of all when you are adding the values of the string you are not actually doing it:
for (int i = 0; i < _updateParams.Length; i++){
dr[0] = i.ToString(); //You need to change this to _updateParams[i].ToString();
//And also concatenate it with "+" for example
}
And also, I'm not sure what language are you using (assume is some .Net based like C#), but should't this "dr[0]" be something like this "dr('YourColumName')", so in the end your code should look something like this:
String tmp = "";
for (int i = 0; i < _updateParams.Length; i++){
tmp = tmp + _updateParams[i].ToString(); //The ToString is not needed if the _updateParams is a String array already
}
dr("YourColumnName") = tmp;
Hope it helps, but if not, please remove your try catch statements to see the error it's throwing and specify the language you are using.

Categories