GridControl fill (NullReferenceException) - c#

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

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.

C# dataview to datatable becomes null

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

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

Using Dataview with a MySQL populated DataGridView

I've taken over some code that I'm a bit unfamiliar with. We were using an access data source to populate a DGV.
I just changed it to fill the DGV from MySQL.
Here's a snip it of code from the Class I'm using to bind:
public void Bind(DataGridView dataGridView)
{
string query = "SELECT * from vwFavoritesList";
mySqlDataAdapter = new MySqlDataAdapter(query, mySqlConnection);
mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
dataTable = new DataTable();
mySqlDataAdapter.Fill(dataTable);
bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
dataGridView.DataSource = bindingSource;
}
I'm having an issue porting over the dataview commands we had before.
Here is the search code that we had before that worked awesome.
private void txtSearch_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(this.dsFavoritesList.gryFavoritesList);
dv.Sort = "Name ASC";
dv.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);
dataGridView1.DataSource = dv;
}
I've come up with:
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);
But when this runs I get this error:
Object reference not set to an instance of an object.
Your DataGridView is already bound to the DataTabe, so you should be able to just do this :-
dataGridView1.DefaultView.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);
You did it right... You have to creat a new DataView and use your DataTable dt.
There is just one mistake, you have to call your dv.RowFilter and set the value in '' like:
private void txtSearch_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(dt);
dv.RowFilter = "Name LIKE '" + txtSearch.Text.Trim() + "'";
dataGridView1.DataSource = dv;
}
I hope this solved your problem! Have a nice day!

RowFilter on a DataTable to display in a gridview

I have the following code which doesn't seem to work. In the Page_Load function I populate the DataSet and display the results in a grid view.
newsCommand = new SqlCommand("SQL code here", dbConnection);
newsDataSet = new DataSet();
newsDataAdapter = new SqlDataAdapter(newsCommand);
newsDataAdapter.SelectCommand = newsCommand;
newsDataAdapter.Fill(newsDataSet, "Bulletins");
if (!Page.IsPostBack)
{
GridViewMain.DataSource = newsDataSet;
GridViewMain.DataBind();
}
I have some links which call this function to filter the data (yearID is passed as a parameter):
DataTable newsTable = new DataTable();
newsTable = newsDataSet.Tables[0];
DataView dvData = new DataView(newsTable);
dvData.RowFilter = "Year > '" + yearID + "'";
GridViewMain.DataSource = dvData;
GridViewMain.DataBind();
Yet the gridview shows the data it orignally loaded, and not the filtered data. The only thing I can think of is that I'm not using the DataTable in the Page_Load function. What else am I missing?
Thanks,
Adrian
Changed the code in the function to:
DataView dataView = newsDataSet.Tables[0].DefaultView;
dataView.RowFilter = "NewsDate2 Like '%" + yearID + "'";
GridViewMain.DataSource = dataView;
GridViewMain.DataBind();
It must have been something in the RowFilter statement.
Filter data from DataTable and display it in Gridview.
string category = ddlcat.SelectedItem.Value; // this can be any input by user
DataTable dt = filter_dt; //filter_dt is DataTable object, contains actual data, from there we will filter
DataView dataView = dt.DefaultView;
if (!string.IsNullOrEmpty(category))
{
dataView.RowFilter = "Category = '" + category + "'";
}
Gridview1.DataSource = dataView;
Gridview1.DataBind();
If any doubt,feel free to ask.
Thank you

Categories

Resources