C# dataview to datatable becomes null - c#

I have a DataTable that I make a DataView with. In the Dataview, I filter and sort the info from the first DataTable. Then I tried to make a new DataTable out of the DataView where I sorted and filtered the content.
Everything seems to work alright but the new DataTable is null, so I lost the content from the original DataTable and the rest of the function does not work anymore. Also, I am getting an Unreachable Code warning in File B # System.Data.DataTable dt480 = dv.ToTable();
I'll keep trying to solve this but I'd like to see if I am way off, or on the right track. Thanks in advance.
I have two files where the code is stored.
File A:
static public void ElecOneLine1(System.Data.DataView dv)
{
string Path = Commands.LoadFile();
System.Data.DataTable table = Commands.ReadExcelToTable(Path);
Commands.ElecDv480V(table);
//Commands.OneLineDt(dv);
Commands.InsertElec1LineBlockscd();
Commands.DrawOneLineBuscd("OneLineBackground", 35.5478, 23.3750, 0, table.Rows[0]);
for (int i = 1; i < 8; i++)
{
Commands.DrawOneLineItem("" + table.Rows[1 + i][0], 4 + ((double)i * 3), 12.6835, 0, table.Rows[0], i + 1);
}
}
File B (called "Commands"):
public static DataView ElecDv480V(System.Data.DataTable dt)
{
System.Data.DataView dv = new DataView(dt);
dv.RowFilter = "F1 = '480V'";
dv.Sort = "F2 ASC, F3 ASC";
return dv;
System.Data.DataTable dt480 = dv.ToTable();
}

return should be the last statement.The return statement terminates execution of the method in which it appears
public static DataView ElecDv480V(System.Data.DataTable dt)
{
System.Data.DataView dv = new DataView(dt);
dv.RowFilter = "F1 = '480V'";
dv.Sort = "F2 ASC, F3 ASC";
System.Data.DataTable dt480 = dv.ToTable();
return dv;
}
Also,You are returning a dataview so you need to have a variable at receiving end also which you are missing.Beside what is the use of setting values for dt480

Related

Datatable filter remove

This filters the datatable correctly:
DataView dv2 = dT.DefaultView;
dv2.RowFilter = "myfiled = " + "1";
dT = dv2.ToTable();
after this:
dT.DefaultView.RowFilter = string.Empty;
The datatable appears empty, I do not understand why.
You can simply use null:
dT.DefaultView.RowFilter = null;
Ok, i solving. Declare DefaultView and dispose her out of for loop and work fine.

GridControl fill (NullReferenceException)

I have devexpress gridcontrol which I want to fill with data from predefined DataTable. This is my code:
private void SortDataTable()
{
DataView dv = GetDataTejbl.DefaultView;
dv.Sort = comboEdit.Text + " " + "DESC";
DataTable SortedDataTable = dv.ToTable();
gridControl1.DataSource = SortedDataTable;
}
The error I get:
"Object reference not set to an instance of an object."
check to determine if the object is null before calling the method
use the "new" keyword to create an object instance
get general help for this exception
Any help would be appreciated. Thank you very much
EDIT: The code I've tried
if (GetDataTejbl.Rows.Count > 0)
private void SortDataTable(){
DataView dv = GetDataTejbl.DefaultView.Sort = "["+comboEdit.Text + "] DESC";
DataTable SortedDataTable = dv.ToTable();
if(SortedDataTable!=null){
gridControl1.DataSource = SortedDataTable;
}
}

DataView RowFilter doesn't filter the Rows on DataGridView

I have this function button_Search1_Click to search for comments that match keywords, then display these flagged comments in dataGridView_flaggedComments.
Next, if there's any changes on the comboBox_stockIndex, I want the filter to take place i.e. filter the flagged comments in dataGridView_flaggedComments with the Tickers_Ticker_ID of 1. But when I do that, all the comments (regardless flagged or not) belong to Tickers_Ticker_ID of 1 display on my dataGridView_flaggedComments. It should have only display the flagged comments for Tickers_Ticker_ID of 1, not all the comments.
I think there's something wrong with the DataSource but I couldn't figure it out. Any help would be very very much appreciated! Thank you!
(If I did miss any similar questions, kindly point it out. Thank you very much!)
private void button_Search1_Click(object sender, EventArgs e)
{
commentCount = 0;
richTextBox_flaggedComments.Clear();
dataGridView_flaggedComments.Refresh();
DataTable flaggedcomments = new DataTable("flaggedcomments");
using (MySqlConnection sqlConn = new MySqlConnection(strProvider))
{
using (MySqlDataAdapter da = new MySqlDataAdapter(
"SELECT Comment_ID, Comments_Date, Author, Title, Comments_Comment, " +
" Tickers_Ticker_ID FROM comments ORDER BY Comments_Date ASC", sqlConn))
{
da.Fill(flaggedcomments);
}
}
StringBuilder sb = new StringBuilder();
string[] words = File.ReadAllLines(sourceDirTemp +
comboBox_crimeKeywords.SelectedItem.ToString() + ".txt");
var query = flaggedcomments.AsEnumerable().Where(r =>
words.Any(wordOrPhrase => Regex.IsMatch(r.Field<string>("Comments_Comment"),
#"\b" + Regex.Escape(wordOrPhrase) + #"\b", RegexOptions.IgnoreCase)));
dataGridView_flaggedComments.DataSource = query.AsDataView();
}
private void comboBox_stockIndex_SelectedIndexChanged(object sender, EventArgs e)
{
DataView dv = dataGridView_flaggedComments.DataSource as DataView;
if (dv == null)
throw new Exception("Bad Data Source type");
else
{
dv.RowFilter = string.Format("Tickers_Ticker_ID = '1'");
dataGridView_flaggedComments.DataSource = dv;
}
}
A DataView as such does not hold any data.
When you set the filter you are effectively replacing the orginal filter in your LinqDataView, that is the Where clause, by the new filter, that is by the RowFilter.
You need to concatenate them to create a double condition.
Since your Where clause uses a complex RegEx I think the easiest way will be to re-use it, appending it with the new, simple 'Tickers_Ticker_ID = ' + id condition.
If you don't want to reapply the original filter you may want to store the filtered rows in a temporary Table. Here I have a DataSet DS and first clone the structure of the 1st Table, name the new Table and add it to the DataSet. When appropriate I copy the filtered rows over from the query:
Set up the Temp Table, where you set up you other DB stuff:
DataSet DS; // if you don't already have one..
// put it at class level!
DS = new DataSet(); // ..create it
DataTable DT = DS.Tables[0].Clone(); // the temp table has the sdame structure
DT.TableName = "temp"; // is called by a name
DS.Tables.Add(DT); // and (optionally) added to the DataSet.
When you do the search you load the data into the temp table:
DS.Tables["temp"].Rows.Clear();
query.CopyToDataTable( DS.Tables["temp"], LoadOption.OverwriteChanges);
DGV.DataSource = DS.Tables["temp"];
Now you can use it in the combo_filter_SelectedIndexChanged event:
string id = ddl_filter.Text;
if (id == "") DGV.DataSource = DS.Tables["temp"];
else
{
DataView dv = new DataView(DS.Tables["temp"])
dv.RowFilter = string.Format("id = " + id) ;
DGV.DataSource = dv;
}
Your filtering wrong... try this instead...
dv.RowFilter = "Tickers_Ticker_ID = 1";

dataTable.DefaultView.Rowfilter always returning first row

I've been trying to make a search function for a dataTable. My problem is that the first row of the table is ALWAYS within the filtered rows, even when the boolean column is actually changed to a zero.
Here is my search code:
private void buscar()
{
DataTable dataTable;
if (!verTodos)
{
dataTable = DBHelper.Instance.ProductosConStock();
}
else
{
dataTable = DBHelper.Instance.ProductosTodos();
}
dataGridProductos.DataSource = dataTable.DefaultView;
foreach (DataGridViewRow row in dataGridProductos.Rows)
{
if (row.Cells[0].Value.ToString().ToUpper().Contains(txtBusqueda.Text.ToString().ToUpper()) ||
row.Cells[1].Value.ToString().ToUpper().Contains(txtBusqueda.Text.ToString().ToUpper()) ||
row.Cells[2].Value.ToString().ToUpper().Contains(txtBusqueda.Text.ToString().ToUpper()))
{
row.Cells[4].Value = 1;
}
else
{
row.Cells[4].Value = 0;
}
}
dataTable.DefaultView.RowFilter = "mostrar = 1";
}
Try creating a DataView from your datatable and run the filter based on that.
Below is a quick example i tried and it works fine.
DataTable dt = new DataTable();
dt.Columns.Add("bool", typeof(Boolean));
dt.Rows.Add(true);
dt.Rows.Add(false);
dt.Rows.Add(true);
DataView dv = new DataView(dt);
dv.RowFilter = "bool = 1";
foreach (DataRowView drv in dv)
{
Console.WriteLine(drv[0].ToString());
}

Using Aggregate functions in DataView filters

i have a DataTable that has a column ("Profit"). What i want is to get the Sum of all the values in this table. I tried to do this in the following manner...
DataTable dsTemp = new DataTable();
dsTemp.Columns.Add("Profit");
DataRow dr = null;
dr = dsTemp.NewRow();
dr["Profit"] = 100;
dsTemp.Rows.Add(dr);
dr = dsTemp.NewRow();
dr["Profit"] = 200;
dsTemp.Rows.Add(dr);
DataView dvTotal = dsTemp.DefaultView;
dvTotal.RowFilter = " SUM ( Profit ) ";
DataTable dt = dvTotal.ToTable();
But i get an error while applying the filter...
how can i get the Sum of the Profit column in a variable
thank you...
Set the datacolumn to a numeric type (int, decimal, whatever):
DataColumn col = new DataColumn("Profit", typeof(int));
dsTemp.Columns.Add(col);
Use Compute:
int total = dsTemp.Compute("Sum(Profit)", "");
Note that aggregation is not a type of filter, which is the main problem with the approach you are tyring.
I used the DataTable's Compute method as suggested, and it works fine. I apply the same filtering as I use for the DataView (which is used to display the sorted and filtered data in the data grid) together with an aggregate function.
string SingleVocheridSale ="1";
DataView view = new DataView(dt);
view.RowFilter = string.Format("VOCHID='" + SingleVocheridSale + "'");
dataGridview1.DataSource = view;
object sumObject;
sumObject = dt.Compute("Sum(NETAMT)", view.RowFilter);
lable1.Text = sumObject.ToString();

Categories

Resources