add texbox values to gridview row in asp.net - asp.net

int Row=0;
Row = PurchaseGridView.Rows.Count;
PurchaseGridView.Rows[Row].Cells[0].Text = ProductNameDropDown.SelectedValue.ToString();
PurchaseGridView.Rows[Row].Cells[1].Text = ProductNameDropDown.SelectedIndex.ToString();
PurchaseGridView.Rows[Row].Cells[2].Text = ProductPriceTxtBox.Text;
PurchaseGridView.Rows[Row].Cells[3].Text = QuantityTxtBox.Text;
PurchaseGridView.Rows[Row].Cells[4].Text = NetPriceTxtBox.Text;
i am adding values of textboxes in gridview like above, but it gives error.
Error: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

You have a few fundamental errors in your code:
You are using the Count to point to a new index which doesn't exists and thus you are getting the index out of range.
You cannot add rows to an asp.net gridview directly. You have to do it through a data binding. Here is an example:
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("ProductNameSelectedValue", typeof(string));
DataColumn dc = new DataColumn("ProductNameSelectedIndex", typeof(int));
..
Rest of you columns
..
DataRow dr = dt.NewRow();
dr["ProductNameSelectedValue"] = ProductNameDropDown.SelectedValue.ToString();
dr["ProductNameSelectedIndex"] = ProductNameDropDown.SelectedIndex;
..
Assign the rest of the columns
..
dt.Rows.Add(dr);
gv.DataSource = dt;
gv.DataBind();

Related

get values of dynamic checkboxes

I am dynamically creating checkboxes in VB.Net and an .aspx page, based on values in my db. I'm placing them in a two column table for ease of alignment. this part works fine.
Private Async Function InitForEditAsync() As Task
Dim docList = Await GetLoanApplicationConfigurationDocs()
Dim row = New HtmlTableRow()
Dim cell = New HtmlTableCell()
Dim i = 0
For Each doc In docList
Dim chkBox = New HtmlInputCheckBox()
Dim lbl = New Label()
Dim remainder = i Mod 2
chkBox.ID = "chkDocId" + doc.Id.ToString
lbl.Text = doc.DisplayName
cell.Controls.Add(chkBox)
cell.Controls.Add(lbl)
row.Cells.Add(cell)
cell = New HtmlTableCell()
If remainder <> 0 OrElse i = docList.Count() - 1 Then
tblEdit.Rows.Add(row)
row = New HtmlTableRow()
End If
i += 1
Next
End Function
Now I need to retrieve the values without knowing the id's but am not having any luck. I tried this:
For Each chkBox As HtmlInputCheckBox In pnlEdit.Controls.OfType(Of HtmlInputCheckBox)
but the checkboxes are not returned in the list of controls. The table is, but there are no rows in the table object when I explored it in the control collection and when I tried this:
For Each row As HtmlTableRow In tblEdit.Rows.OfType(Of HtmlTableRow)
If it will help, here is a Snip of the UI and the HTML that is created:
Any suggestions are appreciated. Thanks in advance.
Based on some ideas I got from another site, I'm going to rewrite this using the asp:CheckBoxList. apparently it binds like a datagrid and you can enumerate through it. Seems like what i need.
UPDATE: Everything I posted to start was resolved with five lines of code! "cblDocList is my asp CheckboxList and docList is my ienumerable of objects.
cblDocList.RepeatColumns = 2
cblDocList.DataSource = docList
cblDocList.DataTextField = "DisplayName"
cblDocList.DataValueField = "Id"
cblDocList.DataBind()
It’s something you can do through a loop for each row and each cell or using Linq to have only cells that have controls of type HtmlInputCheckBox inside.
I have simplified your code to be able run that here also shows you an example to achieve your task. Obviously you must change following your exigences .
Hope I well understood :)
Dim tblEdit As New HtmlTable
For k As Integer = 0 To 10
Dim cell = New HtmlTableCell()
Dim row = New HtmlTableRow()
Dim chkBox = New HtmlInputCheckBox()
Dim lbl = New Label()
Dim remainder = k Mod 2
chkBox.ID = "chkDocId_" + k.ToString
chkBox.Checked = remainder = 0
lbl.Text = "Text indicator of CheckBox nr:" + k.ToString
cell.Controls.Add(chkBox)
cell.Controls.Add(lbl)
row.Cells.Add(cell)
cell = New HtmlTableCell()
tblEdit.Rows.Add(row)
Next
Dim checkBoxes As IEnumerable(Of HtmlInputCheckBox) =
(From mRow In tblEdit.Rows).Select(Function(mr)
Dim cb = (From cc In CType(mr, HtmlTableRow).Cells
Where CType(cc, HtmlTableCell).Controls.OfType(Of HtmlInputCheckBox).Count > 0
Select CType(cc, HtmlTableCell).Controls.OfType(Of HtmlInputCheckBox)()(0)).FirstOrDefault
Return CType(cb, HtmlInputCheckBox)
End Function).ToList
For Each checkBox In checkBoxes
Debug.WriteLine("CheckBox ID: {0} Checked: {1} ", checkBox.ID, checkBox.Checked)
Next

C# DataTable returns blank rows

Hello I am taking data from a one datatable that is coming from a session variable and trying to dump some of the data into new datatable however the new datatable returns empty? Empty meaning that there are rows present in the new table. ie., my gridview returns several blank rows?? Not sure what is happening to the string variables?
string date = DateTime.Now.ToShortDateString();
if (Session["MyData"] != null)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["MyData"];
DataTable newdt = new DataTable();
newdt.Columns.Add(new DataColumn("studentName"));
newdt.Columns.Add(new DataColumn("inter"));
newdt.Columns.Add(new DataColumn("CO"));
newdt.Columns.Add(new DataColumn("teacher"));
newdt.Columns.Add(new DataColumn("date"));
newdt.Columns.Add(new DataColumn("desc"));
DataRow newdr;
foreach (DataRow row in dt.Rows)
{
name = row["NM"].ToString();
term = row["term"].ToString();
Mark = row["Mark"].ToString();
period = row["period"].ToString();
CN = row["CN"].ToString();
CO = row["CO"].ToString();
PID = row["PID"].ToString();
//ADD TO NEW TABLE
newdr = newdt.NewRow();
name = newdr["studentName"].ToString();
dlInter.SelectedText = newdr["inter"].ToString();
CO = newdr["CO"].ToString();
teacher = newdr["teacher"].ToString();
date = newdr["date"].ToString();
LabelDescript.Text = newdr["desc"].ToString();
newdt.Rows.Add();
}
Repeater1.DataSource = newdt;
Repeater1.DataBind();
GridView1.DataSource = newdt;
GridView1.DataBind();
This line is your problem:
newdt.Rows.Add();
This will add an EMPTY row because the call to Add() without a DataRow or an object array is interpreted as adding a row without any value.
The solution is simple
newdt.Rows.Add(newdr);
Also the code before the Add is wrong because you are inverting the variables around the equal sign
newdr["studentName"] = name;
newdr["inter"] = dlInter.SelectedText;
newdr["CO"] = CO;
newdr["teacher"] = teacher
newdr["date"] = date;
newdr["desc"] = LabelDescript.Text;

getting values from a selected item in a dropdownlist in a table cell that was dynamically created in a table in vb code behind

I have created a table dynamically on an asp.net page by creating the rows based of off the number of rows in a dataset from a SQL database. I used a for loop to create my rows and cells with the populated dropdownlists in the page_load() function. My table is created exactly how it needs to be, but I need to get the selected item text for each cell in every row to store back to a database table upon clicking the submit button. I initially have a placeholder on my asp page and replace it with the created table on load. For some reason, when i try to use
For Each r As TableRow In LineupTable.Rows
msgbox(EmployeeDDL.SelectedItem.Text)
Next r
it gives me a null value error for employeeddl.selecteditem.text.
This is how I generate my table.
'Dynamically create table rows and cells and populate them with the proper controls and/or information
Dim numrows As Integer = dtEQP.Rows.Count
Dim numcells As Integer = 6
Dim j As Integer
For j = 0 To numrows - 1
r = New TableRow()
c1 = New TableCell() With {.Width = 300}
c1.Controls.Add(New LiteralControl(dtEQP.Rows(j).ItemArray(0)))
r.Cells.Add(c1)
c2 = New TableCell() With {.Width = 200}
Dim EmployeeDDL As New DropDownList()
EmployeeDDL.DataSource = dsEMP
EmployeeDDL.DataTextField = "FirstName"
EmployeeDDL.DataValueField = "ID"
EmployeeDDL.DataBind()
EmployeeDDL.Items.Insert(0, New ListItem("", "-1"))
c2.Controls.Add(EmployeeDDL)
r.Cells.Add(c2)
c3 = New TableCell() With {.Width = 180}
Dim CodeDDL As New DropDownList()
CodeDDL.Items.Add("0-Running")
CodeDDL.Items.Add("99-Idle")
CodeDDL.Items.Add("60-Down")
CodeDDL.Items.Add("1-Weather")
CodeDDL.SelectedValue = "99-Idle"
c3.Controls.Add(CodeDDL)
r.Cells.Add(c3)
c4 = New TableCell() With {.Width = 100}
Dim RideDDL1 As New DropDownList()
RideDDL1.DataSource = dsRide
RideDDL1.DataTextField = "Ridename"
RideDDL1.DataValueField = "RideID"
RideDDL1.DataBind()
RideDDL1.Items.Insert(0, New ListItem("", "-1"))
c4.Controls.Add(RideDDL1)
r.Cells.Add(c4)
c5 = New TableCell() With {.Width = 200}
Dim OTddl1 As New DropDownList()
OTddl1.DataSource = dsEMP2
OTddl1.DataTextField = "FirstName"
OTddl1.DataValueField = "ID"
OTddl1.DataBind()
OTddl1.Items.Insert(0, New ListItem("", "-1"))
c5.Controls.Add(OTddl1)
r.Cells.Add(c5)
c6 = New TableCell() With {.Width = 350}
Dim CommentsTxtBx As New TextBox()
c6.Controls.Add(CommentsTxtBx)
r.Cells.Add(c6)
LineupTable.Rows.Add(r)
Next j
Any ideas on how I should be retrieving this value in my on click subroutine to get what was actually selected?
First when you add the DropDownList, give it an ID (use your cursor variable to avoid having a duplicate ID):
EmployeeDDL.ID = "EmployeeDDL" & j.ToString()
Secondly, since the DropDownList was dynamically added you need to use FindControl to get an instance of it. Also, make sure SelectedItem is not null/nothing.
Dim intCursor As Integer = 0
For Each r As TableRow In LineupTable.Rows
Dim ddlTarget As DropDownList = Cast(r.Cells(1).FindControl("EmployeeDDL" & intCursor.ToString()), DropDownList)
If Not ddlTarget.SelectedItem Is Nothing Then
Dim strValue = ddlTarget.SelectedItem.Text
End If
intCursor += 1
Next r

Get total of a data row asp.net

Im trying to get the values from each column in a single row to equal a total. Here is the code that im using to achieve this in c# asp.net
DataTable dt = ds.Tables.Add("InspireTable");
string pass = (String)Session["name"];
if (pass.Equals("High"))
{
dt.Columns.Add("Inspire", typeof(string));
dt.Columns.Add("SNS", typeof(int));
dt.Columns.Add("TT", typeof(int));
dt.Columns.Add("Music", typeof(int));
dt.Columns.Add("Total", typeof(string));
DataRow row = dt.NewRow();
row["Inspire"] = "Score";
row["SNS"] = 10;
row["TT"] = 10;
row["Music"] = 0;
dt.Rows.Add(row);
Chart1.DataSource = dt;
this.GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
}
Any ideas? I have tried calling each column and adding them but that seem not to work.
With the old DataTable.Compute method, for example:
int snsTotal = (int) dt.Compute("SUM(SNS)", null); // the second argument is the filter
Here's the "modern" Linq approach:
int snsTotal = dt.AsEnumerable().Sum(r => r.Field<int>("SNS"));
Edit: it seems as if you want to sum the numeric values of each row into a "total"-column. Then you can use a Column-Expression:
dt.Columns.Add("Total", typeof(int), "SNS + TT + Music");

ASP.net Insert blank rows into Gridview

I have a gridview that is bound to a sqldatasource. The Gridview only has a pagesize of 10 and I would like each page to have 10 rows. Therefore if only 5 data rows exist then I would like to add an additional 5 empty rows. Is this easy to do?
Fill your data into data set and count the number of rows retrieved then fill the remaining to the dataset with empty dataRows try this:
Suppose you have a DataSet dt filled with the table or data you want
int remainingRows=10 - dt.Rows.Count;
DataRow dr;
for (int i = 0; i < remainingRows; i++)
{
dr = dt.NewRow();
dr[0] = dr[1] = dr[2] = dr[3] = dr[4] = "";//index goes the no of cols in the table
dt.Rows.Add(dr);
}
dt.AcceptChanges();
grdView.DataSource = dt;
grdView.DataBind();
You can see this
For meeting your requirement , I think you shouldn't use sqldatasource to bind gridview instead of manual binding the datasource to gridview. you can encapsulate a datatable or dataview which each page have 10 rows as the datasource.

Resources