C# Manually added dataset, how to retrieve data to text columns - c#

I have added a dataset to the solution (Windows Form) by "Add"-> New item ->DataSet & created a new tableadapter query that fetches desired data against passed parameter in the design time.
Now I want to assign the data filled in the tableadapter to few textboxes while a button is clicked.
How I can achieve this?

I think I found an answer specific to my situation. I am not sure whether it is the best or the standard, as I am not getting much help with searches, I am accepting my own finding as a solution.
private void getnameid2()
{
PersonDataSet newPersonDataSet = new PersonDataSet(); //PersonDataSet is the manually created dataset
PersonDataSetTableAdapters.L_PEOPLETableAdapter newPersonDataSetTableAdapter = new PersonDataSetTableAdapters.L_PEOPLETableAdapter();
DataTable mytable = new DataTable();
mytable = newPersonDataSetTableAdapter.GetData(decimal.Parse(this.civilidTextbox.Text.ToString()));
//foreach (DataRow row in newPersonDataSetTableAdapter.GetData(decimal.Parse(this.civilidTextbox.Text.ToString()))
foreach (DataRow row in mytable.Rows)
{
nameTextBox.Text = row["FIRST_NAME"].ToString();
personidTextBox.Text = row["PERSON_ID"].ToString();
}
// if (mytable.Rows.Count > 0) { MessageBox.Show(mytable.Rows.Count.ToString()); }
}
Now I am calling the procedure while cell is validating to avoid the already saved transactions being updated while browsing the records, I am checking the transaction id column and calling a return to avoid.
Hope this helps someone else out there or brings the attention of experts who can device better approach :)

Related

DataRow Column Has Value When Read One Way, But Not When Read a Different Way

I'm trying to read values from a DataSet in C#/ASP.NET returned from a stored procedure. Normally, the DefaultView from that DataSet is passed into a GridView in an ASP.NET page. in that event, a particular column I'm interested in has a value. However, if I try to read a DataRow and get the column value, it comes through as empty.
For example, this will display a value:
DataSet ds = //////
DataView dv = ds.Tables[0].DefaultView;
grdQuotes.DataSource = dv;
grdQuotes.DataBind();
This, however, gives me no value:
DataSet ds = //////
foreach (DataRow row in ds.Tables[0].Rows) {
String value1 = (String)row["DOReviewDate"];
String value2 = ((Object)row["DOReviewDate"]).ToString();
String value3 = row.Field<String >("DOReviewDate");
}
All three variables end up empty.
I'm pretty lost on where to go with this, as it's apparent that there's a value being pulled from the SQL database, otherwise it wouldn't display in the GridView table on the page. Also, I can get the rest of the column values in the row without problem. Interestingly enough, there is one other column exhibiting the same behavior.
-- EDIT --
Attempt to iterate through rows and columns to get data:
StringBuilder sb = new StringBuilder();
foreach (DataRow row in ds.Tables[0].Rows)
{
StringBuilder r = new StringBuilder();
foreach (DataColumn c in ds.Tables[0].Columns)
{
r.Append(String.Format("{0} | ", row[c]));
}
r.Append("END");
sb.AppendLine(r.ToString());
}
I was finally able to locate the stored procedure powering this functionality. It's returning empty values for the columns I need. There's nothing but an empty string designating what to return. So, while I can't seem to find the functionality within the page construction, it looks like there is some sort of join or alternate search pulling the data, and I believe I found the table to pull from. Guess I'll just have to take this initial data returned to me and use it to pull from the other table. Or, I guess, maybe make my own SQL search with a join. Either way, the stored procedure does not itself contain a join to the table I need. This is what was in the stored procedure:
'' as DOReviewDate

Comparing DataRows, adding table values dynamically

I think it best I explain my scenario first.
I bring all my data back from a sql database, using SqlDataAdapters, within on transaction.
In an example, I have a college. I want open this college and add modules, and at the same time I wish to add students to these new modules.
These modules and students are saved to their respective DataTable, and the student table has a column relating to it's parent module, "moduleid".
My problem is that I need a way to save both of these in the same transaction, adding the new moduleid to it's child rows. I can create the new modules, and their own moduleid in it's datatable is updated, however when I now need to save the students to this module, I need to add it's moduleid, otherwise it's added to the database without one.
This is my effort so far but I feel I'm barking up the wrong tree.
DataTable dt_new_modules = ds_College.Tables["module"].GetChanges(DataRowState.Added);
da_modules.Update(ds_College.Tables["module"]);
ds_College.Tables["module"].AcceptChanges();
DataTable dt_added = ds_College.Tables["student"].GetChanges(DataRowState.Added);
if (dt_added != null)
{
if (dt_new_modules != null)
{
foreach (DataRow new_module in dt_new_modules.Rows)
{
foreach (DataRow updated_module in ds_College.Tables["module"].Rows)
{
if (updated_module.Equals(new_module))
{
foreach (DataRow new_student in dt_added.Rows)
{
if ((int)new_student["moduleid"] == (int)new_module["moduleid"])
new_student["moduleid"] = (int)updated_module["moduleid"];
}
}
}
}
}
da_student.Update(dt_added);
dt_added.AcceptChanges();
}
DataTable dt_modified = ds_College.Tables["student"].GetChanges(DataRowState.Modified);
if (dt_modified != null)
{
da_student.Update(dt_modified);
dt_modified.AcceptChanges();
}
I am trying to loop through all the added users and if the datarow is the same as the one before it was given it's new moduleid, then get the new id and give it to the user, however I feel there must be a more efficient way to do this.
If I get it right, your problem is with inserting child records for a parent module which was not yet inserted to the DB. I had somewhat the same issue, and using SqlCommandBuilder instead made it work.
Create SqlCommandBuilder (System.Data.SqlClient) objects for each table you are changing, passing the corresponding sqlAdapter as a parameter to the constructor.
It creates the INSERT, UPDATE and DELETE commands automatically, and will handle all the changes made in memory back to the database.
After the command builder objects are created, just call "Update" on the data adapter you had for the parent table (modules), and afterwards "Update" on the children table data adapter.
Hope this solves it.

DataGridView bound with binding list displays blank rows

I have table in my database stored in SQL Server 2012 and through this table I am iterating and adding new object in my binding list. This list is then set as datasource for my DataGridView.
As I understand, the DataGridView should create columns and fill the rows with data, but when I run the build, I only see blank rows. Their count is matching the count of rows in table and I also debugged with breakpoints so I have determined that I really have my datasource filled with data, but I cannot figure those blank rows out.
This is method I use for creating dataset and filling the binding list
public void selectCars()
{
string connString = #"Data Source=POHJOLA\SQLEXPRESS;Initial Catalog=BlueCars;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
string query = "SELECT * FROM Car ORDER BY CarID ASC";
SqlCommand command = new SqlCommand(query, connection);
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
using (DataSet result = new DataSet())
{
adapter.Fill(result);
foreach (DataRow row in result.Tables[0].Rows)
{
carsList.Add(new Car(Convert.ToInt32(row[0]), row[1].ToString(), row[2].ToString(), row[3].ToString(), Convert.ToDecimal(row[4]),Convert.ToInt32(row[5]),row[6].ToString(),row[7].ToString() ));
}
}
}
}
This is my initialization
public managerCarForm()
{
InitializeComponent();
selectCars();
carsGrid.DataSource = carsList;
}
Also I should probably add, that I created columns manually in designer and set datanameproperty to parameters of the car class
I am not getting any exception or error here..
Thanks very much in advance!
I came across the exact same problem in VB.
I Found out that the solution was this:
(I´ll just write my code in VB you can translate it).
Before setting the DataSource of the grid, you should Clear the grid out.
carsGrid.DataSource = Nothing
carsGrid.Rows.Clear()
carsGrid.Columns.Clear()
Then set your grid DataSource as usual. In My case:
carsGrid.DataSource = GetEmptyObject._Get()
Hope it Helps.
foreach (DataRow row in result.Tables[0].Rows)
{
carsList.Add(new Car(Convert.ToInt32(row[0]), row[1].ToString(), row[2].ToString(), row[3].ToString(), Convert.ToDecimal(row[4]),Convert.ToInt32(row[5]),row[6].ToString(),row[7].ToString() ));
}
Please check your carList by applying a breakpoint after foreach loop to verify it contains at least a single data row. And also check your query.
If your application is an ASP.NET
try to modify your code as below..
public managerCarForm()
{
InitializeComponent();
selectCars();
carsGrid.DataSource = carsList;
carsGrid.Databind();
}
Normally this happens when you have manually added the columns in design time.
Or you have AutoGenerateColumns = false;
If you use AutoGenerateColumns = true; the columns will be/should be auto generated.
To solve this:
Right click on the grid -> Edit Columns.
Go to property: DataPropertyName
Set that to the variable name that you bind to (the table column name in your case).
(You say you have done that, but the value here should exactly match what you have in your list. I have made a DTO class and via a loop I have populated a List of my own and set the names to match the properties of that DTO. This should solve it for you.)

How can i get data from a dataset into a list?

I am a newbie in Web Developing. I am using C# in ASP.net
I created a Dataset that includes TableAdapters.
I.e. for my Table Product_family i created the ProductFamilyTableAdapter that includes the following columns prfm_description1, prfm_description2, prfm_description3, etc...
I have a method GetAllProductFamilies.
After that i created a Business Logic Layer class ProductFamiliesBLL.cs which includes the same functions.
In the Page_Load event of my master page i create
ProductFamiliesBLL prfLogic = new ProductFamiliesBLL()
and i can bind to a Datagrid
datagrid1.Datasource = prfLogic.GetAllProductFamilies();
datagrid1.Databind();
My question is if I can add this data into an array or a List and how?
How can i read one by one the retrieved rows and get data from first, second,..., n row from a specific column.
As below you can loop through each row and each column of the row tha....and your code will be likw this...
foreach (DataRow dr in prfLogic.GetAllProductFamilies())
{
foreach(DataColumn dataColumn in myDataTable.Columns)
{
string fieldValue = dr[dataColumn].ToString();
}
}
you can do like this. Try this code.
List<DataRow> list = new List<DataRow>(ds.tables(0).select());
Dont to forget to mark as answer if this helps yu.

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