I have written a function like below
private void PrepUpdate()
{
LicenceBL lbl = new LicenceBL(0);
DataSet lds = new DataSet();
lbl.FetchForEdit(lds, AgentId,BrokerId);
string output ="";
for (int i = 0; i < lds.Tables[0].Rows.Count; i++)
{
output = output + lds.Tables[0].Rows[i]["LicenceTypesNames"].ToString();
output += (i < lds.Tables[0].Rows.Count) ? "," : string.Empty;
}
txtLicenseType.Text = output;
}
It fetch all the LicenceTypesNames from dataset and split them with ',' and then places them in textbox. If dataset contains duplicate entries for licencetypesnames column, they are also inserted in the textbox... Please help me!!!
Here is a Linq approach
var ltnList = lds.Tables[0].Rows.Cast<DataRow>()
.Select(x => x.Field<string>("LicenceTypesNames"));
txtLicenseType.Text = string.Join(",", ltnList.Distinct());
Use HashSet<string>, which takes only unique values in the Add method
private void PrepUpdate()
{
LicenceBL lbl = new LicenceBL(0);
DataSet lds = new DataSet();
lbl.FetchForEdit(lds, AgentId,BrokerId);
HashSet<string> values = new HashSet<string>();
for (int i = 0; i < lds.Tables[0].Rows.Count; i++)
{
values.Add(lds.Tables[0].Rows[i]["LicenceTypesNames"].ToString());
}
txtLicenseType.Text = string.Join(", ", values.ToList());
}
You can use dataview for that;
DataView dv = new DataView(lds.Tables[0]);
DataTable dtLtn = dv.ToTable(true, "LicenceTypesNames");
dtLtn will be consist of distinct values of LicenceTypesNames, then
you can use for loop in the same way
Related
I have the following code :
OleDbDataReader xlsReader =
new OleDbCommand("Select * from [" +spreadSheetName + "]", xlsFileConnection).
ExecuteReader();
In the spreadSheetName parameter i keep my file name.
The connection string for xlsFileConnection was set as
"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source='<directory path>';
Extended Properties='text; HDR=No; FMT=Delimited'"
When i start to execute while (xlsReader.Read()) i take a row #2 but not #1 from data source.
The first suggestion was that HDR parameter has invalid value but it seems it's ok.
There are better and easier ways to reading xlsx files, if I were you I would grab closedXML from nuget and this code to read your excel file into a data table
public void ProcessExcel(string fileName)
{
_dt = ImportSheet(fileName);
dgContacts.ItemsSource = _dt.DefaultView;
}
public static DataTable ImportSheet(string fileName)
{
var datatable = new DataTable();
var workbook = new XLWorkbook(fileName);
var xlWorksheet = workbook.Worksheet(1);
var range = xlWorksheet.Range(xlWorksheet.FirstCellUsed(), xlWorksheet.LastCellUsed());
var col = range.ColumnCount();
var row = range.RowCount();
datatable.Clear();
for (var i = 1; i <= col; i++)
{
var column = xlWorksheet.Cell(1, i);
datatable.Columns.Add(column.Value.ToString());
}
var firstHeadRow = 0;
foreach (var item in range.Rows())
{
if (firstHeadRow != 0)
{
var array = new object[col];
for (var y = 1; y <= col; y++)
{
array[y - 1] = item.Cell(y).Value;
}
datatable.Rows.Add(array);
}
firstHeadRow++;
}
return datatable;
}
The grab the data out of your datatable as you need.
This is live and working code, so you just need to copy and paste
I have requirement where I have to perform calculation on textbox based on formula. I wanted to know how to get the field name and operators separately so that i can bind it in formula textbox. Example : {FieldName1} + {FieldName2}+{Fieldname3} is the formula and i want the data which contains braces separately as they will taken as field name and + symbol separately. I dont know how to get this. Here is my code-
DataTable dt_main = GetTable();
DataTable dt_AutocalculatedColumns = GetCalculatedColumn();
string AutoGeneratedColumnName = string.Empty;
string Formula = string.Empty;
string FLD1 = string.Empty;
string FLD2 = string.Empty;
string FLD3 = string.Empty;
if (dt_AutocalculatedColumns.Rows.Count > 0)
{
foreach (DataRow row_field in dt_AutocalculatedColumns.Rows)
{
AutoGeneratedColumnName = row_field["FieldName"].ToString();
Formula = row_field["AutoCalculatedFormula"].ToString();
string[] words = Formula.Split(' ');
foreach (string Eachword in words)
{
// what to do here i am not getting
}
}
}
protected DataTable GetCalculatedColumn()
{
SqlConnection con= newSqlConnection(ConfigurationManager.ConnectionStrings["ExcelLikeConnnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("My Select Query", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
Any help would be appreciated. Thanks in advance
If you're using only + operator then you should split on it and not on ' '. To make sure that you don't have field name with spaces use trim.
string[] words = Formula.Split('+');
for (int i = 0; i < words.Length; i++)
{
words[i] = words[i].Trim();
}
Of course in this situation you can't have + in field names.
You can also use LINQ:
string formula = "{FieldName1} + {FieldName2}+{Fieldname3}";
string[] words = formula.Split('+')
.Select(w => w.Trim(new char[] {' ', '{', '}'})).ToArray();
This will split the string formula and trim each entry so that you are just left with your field names. The resulting output would be a 3 element array containing FieldName1, FieldName2, and FieldName3.
I have following Code to export data From CSV to Datatable
string cnstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=CSVFilePath;Extended Properties=\"text;HDR=Yes;FMT=Delimited\";";
string sql = "SELECT A,B,C,D FROM Csvfile.csv";
using (OleDbDataAdapter adp = new OleDbDataAdapter(sql, cnstr))
{
DataTable dt = new DataTable();
adp.Fill(dt);
}
But Getting Error as The value of the parameters that are required of one or more has not been set
Query looks Ok for me. As all columns are available in CSV file. Even I tried
string sql = "SELECT [A],[B],[C],[D] FROM Csvfile.csv";
But no Luck.
How to overcome this problem.
Allow me to recommend this as an alternative for reading CSV files
http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
If you define a model class to match what data types you want for your DataTable columns you can use something like this:
public static DataTable CSVToDataTable(string pathToCsv, bool csvHasHeader, Type csvSchema)
{
DataTable dt = new DataTable();
var props = csvSchema.GetProperties();
foreach (PropertyInfo prop in props)
{
dt.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (var line in System.IO.File.ReadAllLines(pathToCsv).Skip(csvHasHeader ? 1 : 0))
{
dt.Rows.Add(CSVLinetoDataRow(line, dt));
}
return dt;
}
private static object[] CSVLinetoDataRow(string csvLine, DataTable dt)
{
//remove commas within quotation marks
var regex = new Regex("\\\"(.*?)\\\"");
string[] values = regex.Replace(csvLine, m => m.Value.Replace(',', ':')).Split(',');
object[] arr = new object[values.Length];
for (int i = 0; i < values.Length; i++)
{
var converter = TypeDescriptor.GetConverter(dt.Columns[i].DataType);
if (values[i] != "\"\"")
{
arr[i] = converter.ConvertFrom(values[i].Replace("\"", ""));
}
else
{
arr[i] = null;
}
}
return arr;
}
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();
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.