Search DataSet and Display Multiple Results(Rows) in TextBoxes - c#

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.

Related

Auto populating text box based on DGV selection

I have a DGV that has data populated through a .json file. When I click on a cell/row I would like to grab the data from the active row to populate a number of textboxes dynamically.
Edits to explain:
below is showing that I did indeed have my text bound to the dataset as Caius had shown me on previous question.
and a bit of code to show that the datagridview is linked to dataset datatable
//json file holding all data to be parsed.
string myDynamicJSON = File.ReadAllText(#"testLibrary.json");
//the data
ToolJson ToolData = JsonConvert.DeserializeObject<ToolJson>
(myDynamicJSON);
//DataTable with something in it, do the binding
BindingSource SBind = new BindingSource();
SBind.DataSource = tooldataSet.Tables["Tool"];
//looks into File finds json fields, and assign them to
variables to be used in C# to create the rows.
foreach (var datum in ToolData.datum)
{
string description = datum.Description;
string vendor = datum.Vendor;
double cost = datum.Cost;
string serial = datum.ProductLink;
string employee = datum.employee;
string location = datum.location;
bool returntool = datum.returnTool;
int onHand = datum.onHandQty;
int stockQty = datum.stockQty;
int orderQty = datum.orderQty;
string toolType = datum.Type;
double diameter = datum.Geometry.Dc;
double OAL = datum.Geometry.Oal;
string productID = datum.ProductId;
//Populate the DataTable with rows of data
DataRow dr = tooldataSet.Tool.NewRow();
// Fill the values
dr["Description"] = description;
dr["Vendor"] = vendor;
dr["Cost"] = cost;
dr["Serial #"] = serial;
dr["Employee"] = employee;
dr["Location"] = location;
dr["OnHand"] = onHand;
dr["StockQty"] =stockQty;
dr["OrderQty"] = orderQty;
dr["Return"] = returntool;
dr["Diameter"] = diameter;
dr["OAL"] = OAL;
dr["Type"] = toolType;
dr["Product Id"] = productID;
//once all data is added to the row, add the row, and loop
untill all data is loaded.
tooldataSet.Tool.Rows.Add(dr);
}
//bind our dataset.table to the gridview
toolDataGridView.DataSource = SBind;
transactionEmployee_Box.Text = "";
transactionSerial_Box.Text = "";
I have found my own answer. The closest i had gotten to getting this accomplished was,
active_Description.text = Convert.ToString(toolDataGridView.CurrentRow.Cells[2]);
but I never realized I can add .value to the end of that and it works just fine.
active_Description.text = Convert.ToString(toolDataGridView.CurrentRow.Cells[2].Value) is what I needed.
I have misc. textboxes in my main form binded
Humor me; it'll take about 2 minutes to do this:
make a new winforms .net framework project
add a DataSet type file to it, open it
right click in the dataset surface and add a datatable
add two columns to the table
switch to the form designer
open the data sources window (view menu >> other windows)
expand every node in the data sources window
drag the table node to the form
drag the two column nodes to the form
run the app, bash 3 rows of data into the dgv with any random test data
click randomly up and down the rows, and see the textboxes change..
..that's data binding!

when CSV has more column headers than a database table during import

I am trying to import csv to mssql using c# code on a asp.net application.
the below c# code helps to load the csv file, choose the table to import to
and then a button click event matches columns and populates a gridview (dgvmatchdata)
the gridview has two columns where the left side column lists all the available table headers from db
and right side column lists all the csv headers in a drop down list.
now, there are 3 conditions
1. both table and csv has equal no. of column headers.
2. table has more columns than csv
3. csv has more columns than table.
i have successfully finished the first two scenarios. and now, i am stuck at the 3rd scenario
my approach to this is,
for example lets consider the table as 10 columns and csv has 15 columns.
i wish to create 15 rows in dgvmatchdata and display the 10 table column headers on the left side
on their own labels for each. the equivalent righ side of the dgvmatchdata will have a drop down list
which contains 'ignore this column' + 15 columns headers from the csv. so, the ddl will now have 16 items.
i want to place text box for the remaining 5 rows on the table column side and i want to populate
the text box with dropdown list. selected items.text during dropdown selected item change event.
now after i have successfully got text inside the remaining 5 text boxes i will write a code on a button click event
to alter table in the db and then the next step would simply import the csv data to the altered table flawlessly.
the point where i am seeking help is, i have placed the text box correctly but the text box disappears on ddl.selecteditem changed
due to post back issue and i am unable to get the text inside the text box.
kindly help.
Gridview Code
protected void dgvmatchdata_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataTable dt = (DataTable)Session["importcsv"];
string[] csvcolNames = (from dc in dt.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
string tablename = ddltable2.SelectedItem.Text;
string[] dbcolNames = loadDataBaseColumns(tablename);
int dbcol = dbcolNames.Length;
int csvcol = csvcolNames.Length;
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlcsvcolumns = (e.Row.FindControl("ddlcsvcolumns") as DropDownList);
ddlcsvcolumns.DataSource = csvcolNames;
ddlcsvcolumns.DataBind();
ddlcsvcolumns.Items.Insert(0, new ListItem("Please select"));
}
for (int i = 0; i < dgvmatchdata.Rows.Count; i++)
{
DropDownList ddlselect = dgvmatchdata.Rows[i].FindControl("ddlcsvcolumns") as DropDownList;
foreach (string col in csvcolNames)
{
string tablcol = ((Label)dgvmatchdata.Rows[i].FindControl("lblcolumns1")).Text;
if (tablcol == col)
{
ddlselect.SelectedItem.Text = col;
ddlselect.Enabled = false;
dgvmatchdata.Rows[i].Cells[1].BackColor = System.Drawing.Color.SpringGreen;
}
}
}
}
Drop Down Selected Index Changed
protected void ddlcsvcolumns_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < dgvmatchdata.Rows.Count; i++)
{
string selectcolumns = ((DropDownList)dgvmatchdata.Rows[i].FindControl("ddlcsvcolumns")).SelectedItem.Text;
Label selectlabel = (dgvmatchdata.Rows[i].FindControl("lblColumns") as Label);
TextBox txtcol = (TextBox)dgvmatchdata.Rows[i].FindControl("txtDynamicText" + i.ToString());
if (selectcolumns.Equals("Please select"))
{
selectlabel.Text = "";
}
else
{
selectlabel.Text = selectcolumns;
}
}
}

select row in winforms grid view

My gridview is populated with Article object like this
var sel = (Article)cmbArticleList.SelectedItem;
DataRow newRow = articlesTable.NewRow();
newRow["CODE"] = sel.Code;
newRow["NAME"] = sel.Name;
newRow["PRICE"] = sel.Price;
articlesTable.Rows.Add(newRow);
articlesGridView.DataSource = articlesTable;
I'm wonder how can I recognize selected row of this grid, for example on LabelSelectedRow.Text should be populated with selected row Code text.
First off you can get your selected rows like so;
//For multiple row selection.
IList rows = dg.SelectedItems;
//For single row selection;
DataRowView row = (DataRowView)dg.SelectedItems[0];
//You can then access them via their column name;
row["yourColumnName"];
//So to assign to say your label..
LabelSelectedRow.Text = row["CODE"] + " " + " row[NAME] + " " + row[PRICE];
Edit: You can put this code in one of the datagrid click events, perhaps RowSelected.

Running Dual GridView Controls to show Summary / Details View

I've got a query to display parts by serial numbers in one column and the number of processes they went through in the other column.
This data is dumped into a GridView control called gvSummary. It works OK now.
What I'd like to do is add a second GridView control called gvDetails next to gvSummary, and replace all of the data in gvSummary with a control that will run a detail query for that particular part when it is clicked.
My plan of attack is to replace the text in the Serial_Number column (Column[0]) with something like the HyperLink control, where the NavigateUrl specifies to call my GetDetails method by passing the text of the Serial_Number.
var table = GetPartsForTimePeriod();
for (int i = 0; i < table.Rows.Count; i++) {
string serialNumber = table.Rows[i][0].ToString().Trim();
var link = new HyperLink()
{
ID = string.Format("lnk{0}", serialNumber.Replace(' ', '_'))
};
link.Text = serialNumber;
link.NavigateUrl = string.Format("GetDetails(\"{0}\"}", serialNumber);
table.Rows[i][0] = link;
}
GridView1.DataSource = table;
GridView1.DataBind();
Issues:
A HyperLink would require a page to load, and all I really want to do is fill this next query into the gvDetails control.
What is the right way to go about this? I generally code WinForms, and I can't think of the way to do this in ASP.NET.

Filling a DataTable based on row values in a DataSet

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

Categories