How to add rows to GridView in asp.net c# application - c#

I've already searched many articles on this page and couldn not find the answer that would fit me.
Ok i have two projects (one is server(host) and one is client). The first one is ASP.NET Empty Web Application and the second one is ASP.NET Web Forms site.
In my host i have code for displaying users from my Entity FrameWork database. And in my client i have a form (atleast im trying to create one) where i should be able to display data (users).
Code for displaying data works fine because i've already used it before.
But somehow i cannot create a code for Gridview, which would put data from database into my cells
Lets say ID column would display user ID...Name column would display user name...
I've already set up service reference.
This is a code i've written so far, but it's giving me a few errors.
GridView1.DataSource = null;
GridView1.Refresh();
ServiceReference1.mojWebServiceSoapClient client = new ServiceReference1.mojWebServiceSoapClient();
var userList = client.getUsers();
foreach (var user in userList)
{
DataTable dt = new DataTable();
DataColumn column = new DataColumn();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Last Name", typeof(string));
}
DataRow row = dt.NewRow();
row[0] = user.userID.ToString();
row[1] = user.Name;
row[2] = user.lName;
dt.Rows.Add(row);
GridView1.DataSource = dt;
GridView1.DataBind();
}
Can you guys please help me fix this? I would really appreciate any input.
Btw this code works, but it only displays 1 user, instead of all (5)

You repeat binding in a for loop and it is incorrect in your case. You should first create a DataTable and next in a for loop add users to it. So the following should satisfy your nedd:
GridView1.DataSource = null;
GridView1.Refresh();
ServiceReference1.mojWebServiceSoapClient client = new ServiceReference1.mojWebServiceSoapClient();
var userList = client.getUsers();
DataTable dt = new DataTable();
DataColumn column = new DataColumn();
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Last Name", typeof(string));
foreach (var user in userList)
{
DataRow row = dt.NewRow();
row[0] = user.userID.ToString();
row[1] = user.Name;
row[2] = user.lName;
dt.Rows.Add(row);
}
GridView1.DataSource = dt;
GridView1.DataBind();
Hope that helped

Related

How do I add a ListBox item to a DataGridView column header [duplicate]

How do create a DataTable in C#?
I did like this:
DataTable dt = new DataTable();
dt.clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
How do I see the structure of DataTable?
Now I want to add ravi for Name and 500 for Marks. How can I do this?
Here's the code:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
DataRow _ravi = dt.NewRow();
_ravi["Name"] = "ravi";
_ravi["Marks"] = "500";
dt.Rows.Add(_ravi);
To see the structure, or rather I'd rephrase it as schema, you can export it to an XML file by doing the following.
To export only the schema/structure, do:
dt.WriteXMLSchema("dtSchemaOrStructure.xml");
Additionally, you can also export your data:
dt.WriteXML("dtDataxml");
You can also pass in an object array as well, like so:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);
Or even:
dt.Rows.Add(new object[] { "Ravi", 500 });
Create DataTable:
DataTable MyTable = new DataTable(); // 1
DataTable MyTableByName = new DataTable("MyTableName"); // 2
Add column to table:
MyTable.Columns.Add("Id", typeof(int));
MyTable.Columns.Add("Name", typeof(string));
Add row to DataTable method 1:
DataRow row = MyTable.NewRow();
row["Id"] = 1;
row["Name"] = "John";
MyTable.Rows.Add(row);
Add row to DataTable method 2:
MyTable.Rows.Add(2, "Ivan");
Add row to DataTable method 3 (Add row from another table by same structure):
MyTable.ImportRow(MyTableByName.Rows[0]);
Add row to DataTable method 4 (Add row from another table):
MyTable.Rows.Add(MyTable2.Rows[0]["Id"], MyTable2.Rows[0]["Name"]);
Add row to DataTable method 5 (Insert row at an index):
MyTable.Rows.InsertAt(row, 8);
// Create a DataTable and add two Columns to it
DataTable dt=new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Age",typeof(int));
// Create a DataRow, add Name and Age data, and add to the DataTable
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad"; // or dr[0]="Mohammad";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);
// Create another DataRow, add Name and Age data, and add to the DataTable
dr=dt.NewRow();
dr["Name"]="Shahnawaz"; // or dr[0]="Shahnawaz";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);
// DataBind to your UI control, if necessary (a GridView, in this example)
GridView1.DataSource=dt;
GridView1.DataBind();
To add a row:
DataRow row = dt.NewRow();
row["Name"] = "Ravi";
row["Marks"] = 500;
dt.Rows.Add(row);
To see the structure:
Table.Columns
You can add Row in a single line
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
You can write one liner using DataRow.Add(params object[] values) instead of four lines.
dt.Rows.Add("Ravi", "500");
As you create new DataTable object, there seems no need to Clear DataTable in very next statement. You can also use DataTable.Columns.AddRange to add columns with on statement. Complete code would be.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Marks") });
dt.Rows.Add("Ravi", "500");
The easiest way is to create a DtaTable as of now
DataTable table = new DataTable
{
Columns = {
"Name", // typeof(string) is implied
{"Marks", typeof(int)}
},
TableName = "MarksTable" //optional
};
table.Rows.Add("ravi", 500);
DataTable dt=new DataTable();
Datacolumn Name = new DataColumn("Name");
Name.DataType= typeoff(string);
Name.AllowDBNull=false; //set as null or not the default is true i.e null
Name.MaxLength=20; //sets the length the default is -1 which is max(no limit)
dt.Columns.Add(Name);
Datacolumn Age = new DataColumn("Age", typeoff(int));`
dt.Columns.Add(Age);
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad Adem"; // or dr[0]="Mohammad Adem";
dr["Age"]=33; // or dr[1]=33;
dt.add.rows(dr);
dr=dt.NewRow();
dr["Name"]="Zahara"; // or dr[0]="Zahara";
dr["Age"]=22; // or dr[1]=22;
dt.rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();
DataTable dt=new DataTable();
DataColumn Name = new DataColumn("Name",typeof(string));
dt.Columns.Add(Name);
DataColumn Age = new DataColumn("Age", typeof(int));`
dt.Columns.Add(Age);
DataRow dr=dt.NewRow();
dr["Name"]="Kavitha Reddy";
dr["Age"]=24;
dt.add.Rows(dr);
dr=dt.NewRow();
dr["Name"]="Kiran Reddy";
dr["Age"]=23;
dt.Rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();
You have to add datarows to your datatable for this.
// Creates a new DataRow with the same schema as the table.
DataRow dr = dt.NewRow();
// Fill the values
dr["Name"] = "Name";
dr["Marks"] = "Marks";
// Add the row to the rows collection
dt.Rows.Add ( dr );
In addition to the other answers.
If you control the structure of the DataTable there is a shortcut for adding rows:
// Assume you have a data table defined as in your example named dt
dt.Rows.Add("Name", "Marks");
The DataRowCollection.Add() method has an overload that takes a param array of objects. This method lets you pass as many values as needed, but they must be in the same order as the columns are defined in the table.
So while this is a convenient way to add row data, it can be risky to use. If the table structure changes your code will fail.
Question 1: How do create a DataTable in C#?
Answer 1:
DataTable dt = new DataTable(); // DataTable created
// Add columns in your DataTable
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
Note: There is no need to Clear() the DataTable after creating it.
Question 2: How to add row(s)?
Answer 2: Add one row:
dt.Rows.Add("Ravi","500");
Add multiple rows: use ForEach loop
DataTable dt2 = (DataTable)Session["CartData"]; // This DataTable contains multiple records
foreach (DataRow dr in dt2.Rows)
{
dt.Rows.Add(dr["Name"], dr["Marks"]);
}
Create datatabe with 2 columns: Name & Marks
IList columns = new List() {"Name", "Marks"};
Datatabel dt = new Datatable();
foreach (string column in columns)
dtSalesOrder.Columns.Add(column, typeof(string));
Add data to datatable
dt.Rows.Add("Ravi","500");

How to display specific row of data based on a column value

From this code I am trying to only display data rows that contain the fields "DBY" in the Station_From_Code column and "MAT" in the Station_To_Column. This will then be printed onto a HTML page. These fields are definitely in the datatable but when I run this cod the table is empty. I am not used to working with data tables in C# so apologies for the poor coding.
dynamic schedluedContent = JsonConvert.DeserializeObject(scheduledJson);
JArray items2 = new JArray();
foreach (JObject stops in schedluedContent.stops)
{
DataTable dt = new DataTable();
DataRow dr;
dr = dt.NewRow();
dr["From_Station_Code"] = stops["station_code"];
dr["To_Station_Code"] = stops["station_code"];
dt.Rows.Add(dr);
DataRow[] result = dt.Select("From_Station_Code = 'DBY' AND To_Station_Code = 'MAT'");
dt.Rows.Add(result);
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();
}
It's a long time I have not seen this style of code for working with database tables! EntityFramework comes to change and surely ease the way of working with database and prevent different risks of using SQL commands inside the code.
If you use EF, your code will become something like bellow:
var rows = myDBContext.MyTable.Where(x=>x.From_Station_Code == "DBY" && x.To_Station_Code == "MAT");
GridViewTrainTimes.DataSource = rows;
You can use find match rows and add in new datatable, that contains only your match rows data then you can bind this dt to gridview.
DataTable dt = new Datatable(); // Lets this datatable have data;
Datatable dt2 = new Datatable(); // Copy all matching rows
foreach (DataRow dr in dt.Rows)
{
if (dr["From_Station_Code"].ToString() == "DBY" && dr["To_Station_Code"].ToString() == "MAT")
{
dt2.Rows.Add(dr);
}
}
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();

How do I search data in from datatable based on user input

I have created one datatable:
DataTable dt=new DataTable();
dt.Columns.Add("Country", typeof(string))
dt.Columns.Add("place", typeof(string))
dt.Columns.Add("Price", typeof(string))
dt.Columns.Add("Desc", typeof(string))
and I have inserted some data in this datatable:
DataRow dtrow = dt.NewRow(); // Create New Row
dtrow["Country"] = "India"; //Bind Data to Columns
dtrow["place"] = "wizag";
dtrow["Price"] = "7520";
dtrow["Desc"] = "Anywhere";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); // Create New Row
dtrow["Country"] = "India"; //Bind Data to Columns
dtrow["place"] = "Goa";
dtrow["price"] = "4500";
dtrow["Desc"] = "Anything";
dt.Rows.Add(dtrow);
I have bind this datatable with my grid view. I have also added one textbox and one search button in mmy aspx page. My requirement is that I want to search data based on user input e.g like 4500 or wizag, and if country name is the same I want to show it in one row
How can I do this?
I would use a DataView in this case
DataView dv = new DataView(dt);
dv.RowFilter = "price = 4500 AND Country = 'India'";
GridView.DataSource = dv.ToTable();
GridView.DataBind();

Remove duplicate web application names from foreach loop

i am new to sharepoint. Can someone tell me how to remove duplicate webapplication names from my code below:
SPFarm farm = SPFarm.Local;
SPWebService webser = farm.Services.GetValue<SPWebService>("");
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Port Numbers", typeof(string));
foreach (SPWebApplication spwebApp in webser.WebApplications)
{
foreach (SPSite site in spwebApp.Sites)
{
DataRow dr = dt.NewRow();
dr[0] = site.WebApplication.Name;
dr[1] = site.Port;
dt.Rows.Add(dr);
}
}
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
Help Highly Appreciated!
i want to display only one name with one port number in the grid.
for instance if there are five sites on web application port no. 2222 it displays 5 times webapplication name with port number 2222. I want it only once.
DataView view = new DataView(dt);
dt = view.ToTable(true, "Name", "Port Numbers");

Change the Column Name in Datatable in C#

I trying to change the column name of the DataTable but some how I lost the data.
foreach (DataRow dr in item)
Ds.Tables[0].ImportRow(dr);
Table.Columns[0].ColumnName = "Barcode";
Table.Columns[1].ColumnName = "Description";
Table.Columns[2].ColumnName = "Price";
Table.Columns[3].ColumnName = "Cost";
Table.Columns[4].ColumnName = "Stock";
Table.Columns[5].ColumnName = "Dept #";
updateDgv.DataSource = Table;
First, the correct code is:
DataTable table = new DataTable();
table.Columns.Add("ItemNo", typeof(string));
table.Columns[0].ColumnName = "Item #";
After your code runs, you have a DataTable with one column named Item #.
There are no rows or data because you didn't add any data. So you didn't lose anything.
I have tested your code and it seems to work fine:
DataTable table = new DataTable();
table.Columns.Add("ItemNo", typeof(string));
table.Columns.Add("ItemName", typeof(string));
DataRow dr = table.NewRow();
dr[0] = "1";
dr[1] = "Name1";
table.Rows.Add(dr);
dr = table.NewRow();
dr[0] = "1";
dr[1] = "Name1";
table.Rows.Add(dr);
table.Columns[0].ColumnName = "Item #";
Probably you are trying to access data through column name later in the code and that is where it is failing. You will not loose the data by just renaming the column name. (Also its a not a good practice use special characters in table column names)
Check out the following screen shots from data visualizer
Before Column Rename:
After Column Rename:

Categories

Resources