Filling a DataTable based on row values in a DataSet - c#

I want to show some news posts on the front page of a website. The news have different categories but are stored in the same mysql database. All news items are loaded into a dataset but from there I just want to extract some specific news and show them in a ListView control.
At the moment I'am using the workaround solution of using a foreach loop on the dataset and formatting the result with html in the code behind. It works but I want all html formatting to be done in the aspx file, thus I'am looking for a better solution.
DataSet articles = db.loadAllArticles();
foreach (DataRow item in articles.Tables["articles"].Select("category = 1"))
{
result += "<h1 class='headline'>" + item["headline"] + "</h1><h2 class='introduction'>" + item["introduction"] + "</h2><p class='content'>" + item["content"] + "</p><p class='authorAndDate'>" + item["author"] + " " + item["datePosted"].ToString().Substring(0,10) + "</p><br/>";
}
lblDisplay.Text = result;
What I was hoping I could do was simply something like this:
DataSet articles = db.loadAllArticles();
ListView1.DataSource = articles.Tables["articles"].Select("category = 1");
ListView1.DataBind();
But the ListView control is not too happy about trying to bind DataRow to it or something.
The best workaround I can think of is to create a new Table within the "articles" DataSet which contains only articles of the chosen category, so something like this:
DataSet articles = db.loadAllArticles();
articles.Tables.Add("frontPageArticles");
articles.Tables["frontPageArticles"] = ???
And then thats where it stops. How can I fill the new datatable with rows from the other datatable where the value of a column is x?
-Eric.

You should be looking at binding you ListView to a DataView, it is filterable and sortable.

You can design your web form using control like repeater, datalist etc. and can bind these control to your datatable on codebehind.
An example can be found here

Related

Correct way of filtering datagrid using datatables in C# WPF

I am creating a WPF application. There is a DataGrid displaying my items and search bar to filter the data. As you know we can't have specific rows from a Dataable to be referenced from another datatable. So the way I'm filtering right now is cloning my original database and adding the rows which matches search bar text to the cloned datatable. After that setting the datagrid's ItemsSource to the cloned datatable to show the filtered rows.
Now the problem is that when I edit my datagrid with filtered rows then obviously that cloned datatable is being modified not the original datatable. So how can I make those changes in the original datatable as well ?
I tried referencing rows from original datatable but that's no possible as one DataRow in memory can have only one container, the original datatable in this case.
EDIT
The answer was simple instead of using 2 DataTable use a DataView which is designed for this very purpose. See the modified code below.
My filter logic:
var filteredTable = dt.Clone();
foreach( DataRow row in dt.Rows)
{
if(row[FilterCategory].ToString().StartsWith(txtb_search.Text))
{
filteredTable.Rows.Add(row.ItemArray);
}
}
ItemsGrid.ItemsSource = filteredTable.DefaultView;
Here is how to do filtering the correct way using DataView. The filter string can have many forms depending on the requirement. sortColumn is filterColumn right now but can be any column to base sort on. Here is a quick tutorial to all this: http://www.csharp-examples.net/dataview-rowfilter/
string filterColumn = dt.Columns[columnIndex].ToString();
string filter = filterColumn + " LIKE '" + txtb_search.Text + "*'";
DataView dv = new DataView(dt, filter, sortColumn , DataViewRowState.CurrentRows);
ItemsGrid.ItemsSource = dv;

Search DataSet and Display Multiple Results(Rows) in TextBoxes

I would like to search my DataSet for a customer name, this name will occur more than once throughout the dataset, meaning there will be more than 1 result (multiple rows returned)
When my search button is clicked, form2 opens up, and in theory should display all rows containing the customer name, but how do I achive this?
I can get it to display 1 row without a problem, but how would I make it display all rows, and the data in textboxes.
At the moment I am using a foreach loop to fill text boxes with returned data, but this only takes data from 1 row within my DataSet.
Is there a way I can make my form auto generate textboxes and populate them will all the data from the array? When I run my query at the moment, it fills the textboxes on form2 with the last rotation of the foreach.
DB Sample
Appreciate any help
Adam
DataRow[] returnedRows;
returnedRows = ds.Tables["Table_Data_1"].Select("cust_name='" + searchFor + "'");
foreach (DataRow returned in returnedRows)
{
tbName.Text = returned[1].ToString();
tbAddress.Text = returned[2].ToString();
tbPhone.Text = returned[3].ToString();
tbMake.Text = returned[4].ToString();
tbModel.Text = returned[5].ToString();
tbReg.Text = returned[6].ToString();
tbYear.Text = returned[7].ToString();
tbParts1.Text = returned[8].ToString();
tbParts2.Text = returned[9].ToString();
tbParts3.Text = returned[10].ToString();
tbParts3.Text = returned[11].ToString();
}
The reason you're having just a single value appear is that you're setting the text of your text boxes to a new value for each row that you've selected. You could change your code to instead add to the Text in the the Textboxes:
tbName.Text += returned[1].ToString() + Environment.NewLine;
Or you could instead bind it to a DataGridView, which is designed to display tabular data. Assuming the DataGridView was named something like customerDataView,
returnedRows = ds.Tables["Table_Data_1"].Select("cust_name='" + searchFor + "'");
var newTable = returnedRows.CopyToDataTable();
BindingSource bindSource = new BindingSource();
bindSource.DataSource = newTable;
var customerDataView.DataSource = bindSource;
You can generate textboxes dinamicaly
Its something like this
foreach (DataRow returned in returnedRows)
{
TextBox txt = new TextBox();
txt.ID = "textBox1"; //generate id dinamically can be a count
txt.Text = returned[1].ToString();
form1.Controls.Add(txt);
}
The way you've implemented the loop override the data in each interation
I've improved the sample code from following this post
https://stackoverflow.com/a/2229040/5252904 answer provided by #rahul.

How to insert multiple dropdownlistbox in gridview?

GridView displays data from different tables so i can't do like there enter link description here or there enter link description here
How it do dynamically?
There my code where I bind GridView:
OracleCommand oracleCom = new OracleCommand();
oracleCom.Connection = oraConnect;
oracleCom.CommandText = "Select * From " + Session["tableNameIns"];
OracleDataAdapter adapter = new OracleDataAdapter();
DataTable tableD = new DataTable();
tableD.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.SelectCommand = oracleCom;
adapter.Fill(tableD);
tableResults.DataSource = tableD.AsDataView();
tableResults.DataBind();
Examples:
1. Table Objects: dropdownlist for column object_type.
2. Table Details: dropdownlist for columns point, object, patch.
3. ...
check here Editable Gridview with Textbox, CheckBox, Radio Button and DropDown List
For drop down list in grid view for editing mode you should set tag EditItemTemplete and binding this grid view from database you should handle RowDataBound event, from this event you can bind drop down list from different tables. And this all are described in the article already.
Just one suggestion that download the source code from reference link try to debug by applying break points to understand briefly...

Secondary sorting in DevExpress GridView

I'm using a DevExpress GridView in my application (My company still uses the old DevExpress v7.2). I have four columns, on which one of them is the "Priority" column. Status is an enumeration with three possible values: Critical, High and Low.
When the user wants to sort the GridView by this column, I want to sort by level of severity but also within the items with severity "Critical" (for example) I want the values to be sorted by date from the earliest to the latest.
If anyone can help that would be awesome.
Thanks!
John.
I'm not sure how your implementing your sorting but you could always intercept looking for a sort on your "Priority" column, then append a secondary sort on the date column.
I've done this type of thing before, mine is overkill for what your looking to do but the basic code would be something like this:
public void GridView_ExampleSorting(object sender, GridViewSortEventArgs e)
{
GridView gv = (GridView)sender;
DataTable dataTable = gv.DataSource as DataTable;
if (dataTable != null)
{
string sortdirection = GetNextSortDirection(e.SortExpression);
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + sortdirection;
if (e.SortExpression.ToString() == "priority")
dataView.Sort += " date DESC";
gv.DataSource = dataView;
gv.PageIndex = 0;
gv.DataBind();
}
}
In the newer versions of the grid control you could hold down the ctrl key and click on the 2'nd coulmn header to sort by that column as well as the 1'st one. But I'm not sure if it will also work on version 7 of the grid.
Update: its actually the shift key. please see here
Also grid have SortBy(columnName) method

Add new rows to a gridview before submit to database

Good afternoon,
I'm developing a form to place orders online.
I get the article from a combobox and get the details of that article using a sql query. So far, so good.
I put that article to a gridview. For one article, it's all ok.
I make the selection of the article, click on insert button, and the article with the details is inserted on the gridview.
My problem is on how to add more rows. When i click the insert button, with a different article and details, i only get one row, with overwritten data.
After all rows are in the gridview, i finally can submit that rows and process the order.
What should i use to add so many rows as i need? ViewState? Session State?
I read some articles, but none of them helped me as i needed.
Thank you.
EDIT:
I use a datatable to store the data.
DataTable DT = new DataTable();
DT.Columns.Add("Artigo");
DT.Columns.Add("Descricao");
DT.Columns.Add("IVA");
DT.Columns.Add("PU");
DT.Columns.Add("UN");
DT.Columns.Add("Qtd");
DT.Columns.Add("TotalLiq");
try
{
int Qtd = Convert.ToInt32(Quantidade.Text);
int PrecoUnit = glb._precolente;
float TotalLiq = Qtd * PrecoUnit;
string str = "SELECT TOP 1 A.Artigo as Artigo, A.Descricao as Descricao, (SELECT Taxa FROM prisalviani.dbo.Iva WHERE Iva = A.Iva)AS IVA, A.UnidadeBase as UN FROM prisalviani.dbo.ARTIGO A where A.Artigo='" + result.ToString() + "'";
ListaLentes = Motor.Consulta(ref str);
while (!ListaLentes.NoFim())
{
DT.Rows.Add(ListaLentes.Valor("Artigo"),
ListaLentes.Valor("Descricao"),
ListaLentes.Valor("IVA"),
PrecoUnit,
ListaLentes.Valor("UN"),
Qtd,
TotalLiq
);
ListaLentes.Seguinte();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
the description you have given is a bit vague, what kind of data structure are you using to hold the order rows? do you want to implement something similar to a shopping basket?
you can implement your own business entities or use a dataset/datatable to hold the new records, you can the keep these objects in the Session.
does it help a bit?
Assuming that your datagridview holds 3 cells of type String,
You can use:
object [] row1 = new object[] { "StringInCell1","StringInCell2","StringInCell3" }
dataGridView.Rows.Add(row1);
And if you need to edit a specific cell you can do it using:
dataGridView.Rows[rowIndex].Cells[cellIndex].Value = "newValue";

Categories