Submitting multiple rows in gridview with Checkboxes (C#) - c#

I am aiming to get data:
From an sql database
To a gridview
To a local table
So far, I am able to use a stored procedure to display the sql data to a gridvew and I am also able to use checkboxes to send the data to a local table.
Issue:
Only one row's data is being submitted to the table, despite the number of checkboxes checked.
ex. I click 3 checkboxes, wanting to get 3 different rows of data to the table. I hit the submit button and when I check the table, only one of the "checked" rows is submitted to the table 3 times.
EDITED Code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["localDataB"].ConnectionString;
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
string insertStatement = "INSERT into LocalDB (Item1, Item2, Item3)" + "(#Item1, #Item2, #Item3)";
string Data1, Data2;
float Data3;
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox ckSel = (gRow.FindControl("checker") as CheckBox);
if (ckSel.Checked)
{
Data1 = Convert.ToString(gRow.Cells[1].Text);
Data2 = Convert.ToString(gRow.Cells[2].Text);
Data3 = Convert.ToInt32(gRow.Cells[3].Text);
using (var sqlCommand = new SqlCommand(insertStatement, sqlConnection))
{
sqlCommand.Parameters.Add("Item1", SqlDbType.Text).Value = Data1;
sqlCommand.Parameters.Add("Item2", SqlDbType.Text).Value = Data2;
sqlCommand.Parameters.Add("Item3", SqlDbType.Float).Value = Data3;
sqlCommand.ExecuteNonQuery();
}
}
}
}
GVbind();
Code for checkbox inside grid:
<asp:GridView ID="GridView1" runat="server" EmptyDataText="No Data Found" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4"
AutoGenerateColumns="False" CellSpacing="2" ForeColor="Black" DataKeyNames="Data1" Width="70%" Visible="False" ShowFooter="True">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="SelectBox" runat="server" Text="Select"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="checker" runat="server" OnCheckedChanged="checker_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Data1" HeaderText="Title1" ReadOnly="True" />
<asp:BoundField DataField="Data2" HeaderText="Title2" ReadOnly="True" />
<asp:BoundField DataField="Data3" HeaderText="Title3" />
</Columns>
</asp:GridView>

Ok, it not at all clear what your routine checker_CheckedChanged() does?
You don't need a post-back or anything for the check boxes - but ONLY the one submit button and code stub
. Those data1, data2 etc. will NOT persist in memory anyway. So, you can't use that routine - but you don't need it either.
Unless the grid has multiple pages etc., then dump that routine. You are free to check box any row in the grid. You then have one submit button code, and that routine just needs a bit of change to check all GV rows, and save the check box values.
That submit button code thus can/will look like this:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["localDataB"].ConnectionString;
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
// insert any row with check boxes into temp db
string insertStatement = "INSERT into LocalDB (Item1, Item2, Item3) " +
"values (#Item1, #Item2, #Item3)";
bool Data1, Data2, Data3;
foreach (GridViewRow gRow in GridView1.Rows)
{
Data1 = Convert.ToBoolean(gRow.Cells[0].ToString());
Data2 = Convert.ToBoolean(gRow.Cells[1].ToString());
Data3 = Convert.ToBoolean(gRow.Cells[2].ToString());
// save data if ANY is checked
if (Data1 | Data2 | Data3)
{
using (var sqlCommand = new SqlCommand(insertStatement, sqlConnection))
{
sqlCommand.Parameters.Add("#Item1", SqlDbType.Bit).Value = Data1;
sqlCommand.Parameters.Add("#Item2", SqlDbType.Bit).Value = Data2;
sqlCommand.Parameters.Add("#Item3", SqlDbType.Bit).Value = Data3;
sqlCommand.ExecuteNonQuery();
}
}
}
}
GVbind();
}
I don't see the need for your first routine. The submit button can loop the GV, get the check box values, and if any one of the 3 is checked, then you do the insert.
However, keep in mind that the cells[] collection ONLY works for datafields if you using a templated control and REAL check box, then you need to use findcontrol, and NOT the cells[] collection
Edit:
Ok, first, information provided suggests that a template field is being used.
HOWEVER, we will first address the CheckBoxField code, since it HARD to google and find that answer. So I going to include that answer.
If a check box is a datafield, then you can't change/edit, but you STILL MAY want to iterate over the GV, and get those values.
So, for data fields, say like this:
<asp:CheckBoxField DataField="Active" HeaderText="Active" />
Then our code has to work like this (you have to dig deeper into cells() colleciton.
So, code becomes this:
foreach (GridViewRow gRow in GridView1.Rows)
{
Data1 =(gRow.Cells[0].Controls[0] as CheckBox).Checked;
Data2 = (gRow.Cells[1].Controls[0] as CheckBox).Checked;
Data3 = (gRow.Cells[2].Controls[0] as CheckBox).Checked;
Note how a CheckBoxField requires us to use controls.
However, as noted, with template field (any kind and ANY of them?).
WE DO NOT use the Cells[] collection and templated columns DO NOT appear in the cells collection.
And thus, in a lot (probably most) cases, then we can expect to have a CheckBox control dropped into the markup as a templated field.
Typical looks like this:
<asp:GridView ID="GridView1" runat="server" class="table borderhide"
AutoGenerateColumns="false" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Smoking" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkSmoking" runat="server"
Checked='<%# Eval("Smoking") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Balcony" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkBalcony" runat="server"
Checked='<%# Eval("Balcony") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So in above, the first values (bound fields) WILL BE found in cells colleciton.
However, the templated fields above? we have to do this:
"WHERE ID = #ID";
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox cSmoke = (CheckBox)gRow.FindControl("chkSmoking");
CheckBox cBlacony = (CheckBox)gRow.FindControl("chkBalcony");
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#S", SqlDbType.Bit).Value = cSmoke.Checked;
cmdSQL.Parameters.Add("#B", SqlDbType.Bit).Value = cBlacony.Checked;
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
cmdSQL.ExecuteNonQuery();
}
}
So, our code then becomes this:
foreach (GridViewRow gRow in GridView1.Rows)
{
Data1 =(gRow.FindControl("Active") as CheckBox).Checked;
Data2 = (gRow.FindControl("Smoking") as CheckBox).Checked;
Data3 = (gRow.FindControl("Balcony") as CheckBox).Checked;
Now of course, you replace the "Text control" id with YOUR data 1, 2, and 3 id that you used.
The rest of the code should be the same.
BIG LESSON OF THE DAY?
Post a wee bit of markup - not a huge boatload - but just a few lines next time. You save world poverty, and I would have been able to post a better answer next time.
So the rule is:
DataBound fields - use cells[] collection.
Templated fields - you have to using .FindControl("name of control id goes here")
Edit#2
Ok, so far, the question is now this:
We have some data. If the user checks the row 1, or 5 or 10 rows, for each of the checked rows, I want to write out the columns/values I have in 3 other columns item1, item2, item3?
Simple queston!!!!
Ok, so the ONLY missing information is WHAT data type field type is item1, item2, and item3? We only really are missing that part.
So, if check box = true, write out those 3 item columns to the new temp table.
So, the code now should be:
bool Data1, Data2, Data3;
foreach (GridViewRow gRow in GridView1.Rows)
{
// get check box -
CheckBox ckSel = (gRow.FindControl("checker") as CheckBox);
// save data if ANY is checked
if (ckSel.Checked)
{
Data1 = Convert.ToBoolean(gRow.Cells[0].Text);
Data2 = Convert.ToBoolean(gRow.Cells[1].Text);
Data3 = Convert.ToBoolean(gRow.Cells[2].Text);
using (var sqlCommand = new SqlCommand(insertStatement, sqlConnection))
{
sqlCommand.Parameters.Add("#Item1", SqlDbType.Bit).Value = Data1;
sqlCommand.Parameters.Add("#Item2", SqlDbType.Bit).Value = Data2;
sqlCommand.Parameters.Add("#Item3", SqlDbType.Bit).Value = Data3;
sqlCommand.ExecuteNonQuery();
}
}
}
As noted, I stated MULTIPLE TIMES NOW, that non templated columns STILL MUST use cells collection. ONLY templated columns can and need to use FindControl. All others MUST continue to use .Cells[] collection.

It should be like this;
sqlCommand.Parameters.AddWithValue("#Item1", data1);
sqlCommand.Parameters.AddWithValue("#Item2", data2);
sqlCommand.Parameters.AddWithValue("#Item3", data3);

Related

How can I get the distinct values in a Gridview column and store them into a Datatable or list?

I have a Gridview in a C# ASPX Page called Gridview1 that pulls a Table from a SQL Server and displays it on PageLoad.
There are 10 columns in the Gridview and I need all the distinct values in column 7 which is Code
Code
A
C
D
A
A
D
B
E
R
A
A
C
B
Basically I need some kind of structure, list or even a datatable to get all the distinct values from the Column "Code". From the example above it would be a list or datatable with 6 entries since there are 6 unique codes in the Gridview column.
Distinct
A
B
C
D
E
R
Any ideas how this can be implemented?
Well, ALWAYS but always try to do such code against the data source and NOT the web page HTML (be it a list view, or grid view, repeater or whatever). The web page is for display of the data, not data base stuff.
Now, I suppose in this case, we could operate against the grid, but it usually a WHOLE lot easier to operate against the data.
So, say this grid:
<div style="float:left;width:40%">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
CssClass="table table-hover table-striped"
DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdDel" runat="server"
Text="Delete"
CssClass="btn"
onclick="cmdDel_Click"
onclientClick="return confirm('really delete this?');"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div style="float:left;margin-left:40px">
<h4>City list</h4>
<asp:ListBox ID="ListBox1" runat="server"
DataTextField="City"
DataValueField="City" Width="163px" Height="159px"
></asp:ListBox>
</div>
</div>
So, right next to the grid, I have a list box we will list out each seperate city.
So, code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
DataTable rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName");
GridView1.DataSource = rstData;
GridView1.DataBind();
// now fill out a list box of each city
DataTable rstCity = new DataTable();
rstCity = rstData.DefaultView.ToTable(true, "City");
rstCity.DefaultView.Sort = "City";
ListBox1.DataSource = rstCity;
ListBox1.DataBind();
}
And we get this:
So, NOTE how we went to the data source - NOT the grid (the grid is not a database and in most cases we should not think of the grid as such).
However, we could also pull the values out of the grid (can't see why we would do this).
So, lets drop in listbox 2, and add this code that operates against the grid:
our 2nd listbox - this time NOT data bound.
So, this:
<div style="float:left;margin-left:40px">
<h4>City list 2nd example</h4>
<asp:ListBox ID="ListBox2" runat="server"
DataTextField="Text"
DataValueField="Value"
Width="163px" Height="159px"
></asp:ListBox>
</div>
And say a button click or whatever - we run this code to fill out 2nd listbox from the data grid.
FYI:
If you using templated fields, then you have to use findcontrol to get the control.
If you using data fields, then you use .cells[] array/collection.
but, CAUTION, since empty cells will render as a non breaking space &nsb;
So, we convert from html, just to be save, and we have this code:
protected void Button1_Click1(object sender, EventArgs e)
{
List<string> CityList = new List<string>();
foreach (GridViewRow gRow in GridView1.Rows)
{
string sCity = Server.HtmlDecode(gRow.Cells[2].Text);
if (!CityList.Contains(sCity))
CityList.Add(sCity);
}
// display our list in 2nd listbox
CityList.Sort();
foreach (string sCity in CityList)
{
ListBox2.Items.Add(new ListItem(sCity, sCity));
}
}
So, now we have this:
So try to operatee against the data. I mean, we could even say get a list of distinct citys wiht a query, say this:
string strSQL = "SELECT City from tblHotels GROUP BY City";
Datatable rstCity = MyRst(strSQL);
ListBox1.DataSource = rstCity;
ListBox1.DataBind();
So, in most cases??
Much less effort and better to get this data from the data source, and NOT go to the GV - as it is a display and render system - not a data base, nor is it a data source.
Now, in above, I used a helper function MyRst. All that does is return a table based on sql - (became VERY tired very fast having to type that type of code over and over). So that was this:
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}

Dropdownlist based on database and to merge column when they have same ID

I have the examples of data saved in the database as shown in the figure:
list of attachments uploaded by 3 different users (STAFF_145, STAFF_143 and STAFF_147)
When I called it from gridview list, it shows like this:
Gridview of list attachment
Based on the gridview, I tried to apply the "Attachments & TRF" column with <asp:Label ID="txt_training_attach_name" runat="server" Text='<%# Bind("training_attach_name") %>' ReadOnly="true">.
It shows error when I've change to "Dropdownlist" instead of using "Label" or "Textbox".
System.ArgumentOutOfRangeException: ''txt_training_attach_name' has a
SelectedValue which is invalid because it does not exist in the list
of items. Parameter name: value'
The error points out at here when I used Dropdownlist:
if (dt.Rows.Count > 0)
{
Grid_Attachment.DataSource = dt;
Grid_Attachment.DataBind();
}
It is possible if I want to make a gridview as shown as like this?
Dropdownlist and Merge Column
I've try many ways since last month but I still cannot get the answer. Appreciate if you could help me. Thank you in advanced.
You don't mention if the staff table of up-loaded files is a different table then the one that supposed to drive the grid.
if it is for some reason, then build a group by query that does not include the file(s) column, and group by so you wind up with a SINGLE row for each staff member.
So, then we can drop in a grid list this:
And I am going to use a listbox in place of a combo (dropdown), so it will NICE display the files - you can change that to a dropdown if you want - same code
So, the markup might be this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table table-hover" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="TrainingDate" HeaderText="Training Date" DataFormatString="{0:yyyy-MM-dd}" />
<asp:BoundField DataField="ApplicationDate" HeaderText="Application Date" DataFormatString="{0:yyyy-MM-dd}" />
<asp:BoundField DataField="ProgramTitle" HeaderText="Program Title" />
<asp:BoundField DataField="TrainingCost" HeaderText="Training Cost" DataFormatString="{0:c}" />
<asp:TemplateField HeaderText="Documents Submitted">
<ItemTemplate>
<asp:ListBox ID="cboFiles" runat="server" Width="200PX"
DataTextField ="FileName"
DataValueField="FileName">
</asp:ListBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Note how we added a listbox (as noted, use a drop down if you want).
So, the code to fill this gv would thus be this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
GridView1.DataSource = MyRst("SELECT * from Users ORDER BY FirstName");
GridView1.DataBind();
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
However, for each row, we need to load up the list of files for that one row. As noted, I don't know if you have two tables here - or one. (but, it really does not matter - as noted, use a group-by for this main grid data source.
Now, the only extra part is to use the gv "row data bound" event. This fires for each row during render, and is the idea event to load up the combo or list box.
That code is thus this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// get PK row id (user id)
int? PKID = GridView1.DataKeys[e.Row.RowIndex]["ID"] as int?;
string strSQL = "SELECT FileName FROM MyFiles WHERE User_ID = " + PKID;
DataTable rstFiles = MyRst(strSQL);
ListBox cboFiles = e.Row.FindControl("cboFiles") as ListBox;
cboFiles.DataSource = rstFiles;
cboFiles.DataBind();
cboFiles.Rows = 1;
if (rstFiles.Rows.Count > 1)
cboFiles.Rows = rstFiles.Rows.Count;
}
}
And above I do have two columns. One is JUST file name, and one column is the full path name + file to the up-load folder. If you don't have just a file name column, then we can write a bit of code to JUST include + show file name.
the results of running the above is thus this:

Selected Items per listbox instead of all selected items in one listbox

My listbox is selecting the values correctly, but it is separating the values per listbox instead of inserting all of the values in one list box.
Why is this behavior happening?
Code Behind
protected void GvInBlocks_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
List<string> list = new List<string>();
//Find listBoxCourse in GvChildBlock
ListBox listBoxCourse = e.Row.FindControl("listBoxCourse") as ListBox;
getCourseLB(listBoxCourse);
//Fill control
string CourseNames = (e.Row.FindControl("lblChildBlockCourse") as Label).Text;
list.Add(CourseNames);
foreach(ListItem items in listBoxCourse.Items)
{
if(list.Contains(items.Value))
{
items.Selected = true;
}
}
}
}
MarkUp Language
<asp:Panel ID="pnlInBlocks" runat="server" Style="display: none">
<asp:GridView ID="GvInBlocks" runat="server" AutoGenerateColumns="false" CssClass="list" OnRowDataBound="GvInBlocks_RowDataBound">
<Columns>
<asp:TemplateField HeaderText = "Curso">
<ItemTemplate>
<asp:Label ID="lblChildBlockCourse" runat="server" Text='<%# Eval("CourseID") %>' Visible = "false" />
<asp:ListBox ID="listBoxCourse" runat="server" SelectionMode="Multiple">
</asp:ListBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
EDIT:
I edited the code and I did separate the values by a comma but the results remain the same , is it because of the RowDataBound? If the database returns 2 rows is it going to return 2 list boxes?
Code Edited:
//Find listBoxCourse in GvChildBlock
ListBox listBoxCourse = e.Row.FindControl("listBoxCourse") as ListBox;
getCourseLB(listBoxCourse);
//Fill control
string CourseNames = (e.Row.FindControl("lblChildBlockCourse") as Label).Text;
string[] arrayNames = CourseNames.Split(',');
foreach(var names in arrayNames)
{
listBoxCourse.Items.FindByValue(names).Selected = true;
}
So the course list is like say:
Physics 204, Math 220, Computing 220
So, then you need to split above into a "list" for the listbox
eg:
//Fill control
string CourseNames = (e.Row.FindControl("lblChildBlockCourse") as Label).Text;
CourseNames = CourseNames.Repace(", ",","); ' remove blanks
List<string> slCourse = (List<string>)CourseNames.Split(',').ToList();
listBoxCourse.DataSource = slCourse;
listBoxCourse.DataBind();
Now, your list box is filled up with values.
Or is there a 100% separate list of choices that supposed to drive the listbox, and you only want to select/set ONE course name as the selected value in listbox?
Ok, for some VERY strange design, we should have this setup:
You have some students, a table of the coures they are taking, and the 3rd table is really just a list of all courses.
but, for some strange reason, we don't have the courses table, and have this:
Worse, we some how have "one" column that has the list of "id" the student is taking (again, breaks every rule - makes ANY kind of solution very difficult).
And even worse yet? The desired output is to display ALL courses for each row, and ONLY highlight the one the student is enrolled.
Seems to me that that each row should ONLY show their courses, and not all of them, and then in that list show the highlighted ones.
But, lets go with this "VERY strange from another planet question that does not make sense to do it this way.
So, we have to fill up the grid, (easy). We also have to drop in a listbox of ALL COURSES.
So, lets do this part first, and THEN we work on the highlight part.
So, we have this grid - a few columns, and list box
<div style="width:40%;padding:35px">
<asp:GridView ID="GVStudents" runat="server" CssClass="table" AutoGenerateColumns="False"
DataKeyNames="ID" OnRowDataBound="GVStudents_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="CourseIDList" HeaderText="CourseIDList" />
<asp:TemplateField HeaderText="Courses" HeaderStyle-Width="190px">
<ItemTemplate>
<asp:ListBox ID="LstCourses" runat="server" Style="Height:120px;width:170px"
DataValueField ="ID"
DataTextField ="Course">
</asp:ListBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Ok, now the code to fill this up:
public partial class StudentListBox1 : System.Web.UI.Page
{
DataTable rstCourses = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
rstCourses = MyRst("SELECT ID, Course from Courses ORDER BY Course");
// load grid
GVStudents.DataSource = MyRst("SELECT * FROM Students Order by FirstName");
GVStudents.DataBind();
}
protected void GVStudents_RowDataBound(object sender, GridViewRowEventArgs e)
{
// for each row, load up listbox with courses
if (e.Row.RowType == DataControlRowType.DataRow)
{
ListBox lv = (ListBox)e.Row.FindControl("LstCourses");
lv.DataSource = rstCourses;
lv.DataBind();
}
}
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
using (SqlCommand cmdSQL = new SqlCommand(strSQL, con))
{
con.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
return rstData;
}
And now out output is this:
So the next bit of code would be to take that id list from that one column, and high light the courses in the course listbox. (and if that works, then we can remove the "id list" row in that grid. So, lets write that part to highlight the courses.
The code would/could be:
(we add right after the databind code that filled the listbox.
So we now from above have this:
protected void GVStudents_RowDataBound(object sender, GridViewRowEventArgs e)
{
// for each row, load up listbox with courses
if (e.Row.RowType == DataControlRowType.DataRow)
{
ListBox lv = (ListBox)e.Row.FindControl("LstCourses");
lv.DataSource = rstCourses;
lv.DataBind();
// get "item list" column (we NOT use from grid, since we plan to remove
// from grid display - so, get this from the data source
DataRowView gData = (DataRowView)e.Row.DataItem;
List<string> sIdList = gData["CourseIDList"].ToString().Split(' ').ToList();
foreach (ListItem lBox in lv.Items)
{
lBox.Selected = sIdList.Contains(lBox.Value);
}
}
}
And now we have this output:
Now, it does seem to me, it would be better to show JUST the courses they have in each list box.
On the other hand, I suppose we could start using the above to tick off (select more courses for each user). And we could use the above grid for this.
Edit ===========================================
Ok, so we now have more information and that each row DOES NOT have a list of courses as "id" separated by some delimited.
so, we can dump the id list list column, and now have just student information in the one line + a list box of courses like this:
<asp:GridView ID="GVStudents" runat="server" CssClass="table" AutoGenerateColumns="False"
DataKeyNames="ID" OnRowDataBound="GVStudents_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:TemplateField HeaderText="Courses" HeaderStyle-Width="190px">
<ItemTemplate>
<asp:ListBox ID="LstCourses" runat="server" Style="Height:120px;width:170px"
DataValueField ="ID"
DataTextField ="Course"
SelectionMode="Multiple"
SelectMethod="">
</asp:ListBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And now our code to fill out the list box becomes this:
protected void GVStudents_RowDataBound(object sender, GridViewRowEventArgs e)
{
// for each row, load up listbox with courses
if (e.Row.RowType == DataControlRowType.DataRow)
{
ListBox lv = (ListBox)e.Row.FindControl("LstCourses");
lv.DataSource = rstCourses;
lv.DataBind();
// now get all courses for this student
DataRowView gData = (DataRowView)e.Row.DataItem;
int StudentPK = (int)gData["ID"];
DataTable rstStudentCourses;
string strSQL = "SELECT Course_ID FROM StudentCourses WHERE Student_ID = " + StudentPK;
rstStudentCourses = MyRst(strSQL);
foreach (ListItem lBox in lv.Items)
{
string sFind = "Course_ID = " + lBox.Value;
lBox.Selected = (rstStudentCourses.Select(sFind).Count() > 0);
}
}
And out output is this:
As noted, it might be better for each row to ONLY show the courses taken, and not just highlight out of ALL possible courses.
Of course this is a easy change, and we would DUMP the global scoped courses datatable, and simple pull course list for each row, and directly fill the list box with those courses (it would be less code, since no matching loop against the whole course list in the list box would now be required. (but just query to fill listbox with ONLY courses for the one row/student).

Copy Paste a row in a asp:GridView using C# in a web application

So I have a web application that uses a GridView.
We currently add 1 new blank record at a time fill it in and move on. There are times when the data needing to be entered has several fields that need to be duplicated. Is there a way to add a blank row, fill it in , and then copy that row and paste it back into the GridView?
I've looked at clone, but i haven't seen anything that works in a web application. Thanks for any advice.
Well, one way, is you could add a copy button to the grid?
Say we have this grid:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
cssclass="table table-hover borderhide">
<Columns>
<asp:TemplateField HeaderText ="First Name">
<ItemTemplate>
<asp:TextBox ID="txtFirst" runat="server" Text = '<%# Eval("FirstName") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Last Name">
<ItemTemplate>
<asp:TextBox ID="txtLast" runat="server" Text = '<%# Eval("LastName") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="City">
<ItemTemplate>
<asp:TextBox ID="txtCity" runat="server" Text = '<%# Eval("City") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Active">
<ItemTemplate>
<asp:CheckBox ID="Active" runat="server" Checked = '<%# Eval("Active") %>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Copy">
<ItemTemplate>
<asp:ImageButton ID="cmdCopy" runat="server" Text="Copy"
ImageUrl="~/Content/copy1600.png" Height="32px" Width="32px"
OnClick="cmdCopy_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdSave" runat="server" Text="Save" CssClass="btn-primary" OnClick="cmdSave_Click1" />
<asp:Button ID="cmdAdd" runat="server" Text="Add Row" CssClass="btn-primary" style="margin-left:20px" OnClick="cmdAdd_Click1"/>
<br />
So, code to load this grid up
private DataTable rstPeople = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
ViewState["MyTable"] = rstPeople;
}
else
rstPeople = (DataTable)ViewState["MyTable"];
}
public void LoadGrid()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from People",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
rstPeople.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstPeople;
GridView1.DataBind();
}
}
And the add row button code:
protected void cmdAdd_Click1(object sender, EventArgs e)
{
GridToTable(); // user may have edits
// add a new row to the grid
DataRow OneRow = rstPeople.NewRow();
OneRow["Age"] = 0;
OneRow["Active"] = true;
rstPeople.Rows.Add(OneRow);
GridView1.DataSource = rstPeople;
GridView1.DataBind();
}
So we click on add row, and that gives us this:
So, we have that blank row. But, in place of add row, we could click the copy button, and that would add a row - but copy from current. (I suppose we could have a copy + paste button - but that's WAY TOO much UI here).
So, add row = add blank row.
but, copy row button - add row - copy.
The code for that looks like this:
protected void cmdCopy_Click(object sender, ImageClickEventArgs e)
{
GridToTable(); // user might have done some editing
ImageButton cmdCopy = (ImageButton)sender;
GridViewRow gvRow = (GridViewRow)cmdCopy.Parent.Parent;
DataRow CopyFrom = rstPeople.Rows[gvRow.RowIndex];
DataRow OneRow = rstPeople.NewRow();
OneRow["Age"] = 0;
OneRow["FirstName"] = CopyFrom["FirstName"];
OneRow["LastName"] = CopyFrom["LastName"];
OneRow["City"] = CopyFrom["City"];
OneRow["Active"] = CopyFrom["Active"];
rstPeople.Rows.Add(OneRow);
GridView1.DataSource = rstPeople;
GridView1.DataBind();
}
Now I not shared how teh save button works.
So, the user now can add new rows. Tab around - edit any row. or even copy a new row (and again, edit some more).
So save the whole mess and grid back to the database, we
Send Grid back to table
Send table back to database.
So the save all button is thus this:
protected void cmdSave_Click1(object sender, EventArgs e)
{
GridToTable();
// now send table back to database with updates
string strSQL = "SELECT ID, FirstName, LastName, City, Active from People WHERE ID = 0";
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
SqlDataAdapter daupdate = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder cmdBuild = new SqlCommandBuilder(daupdate);
daupdate.Update(rstPeople);
}
}
again, really simple. And note how we did not bother with templates etc. (too messy, and really not less code then above).
I suppose you could have for a new row a "paste" icon, but if the users going to have to pick a row and copy - might as well make it "add row + copy" in one operation.
(and it not really a copy button, but more of a "duplicate row" button.
Only routine not posted was the GridToTable. This works, since we always persist the table, but any edits in GV have to be send back to the table, and thus we use this:
void GridToTable()
{
// pull grid rows back to table.
foreach (GridViewRow rRow in GridView1.Rows)
{
int RecordPtr = rRow.RowIndex;
DataRow OneDataRow;
OneDataRow = rstPeople.Rows[RecordPtr];
OneDataRow["FirstName"] = ((TextBox)rRow.FindControl("txtFirst")).Text;
OneDataRow["LastName"] = ((TextBox)rRow.FindControl("txtLast")).Text;
OneDataRow["City"] = ((TextBox)rRow.FindControl("txtCity")).Text;
OneDataRow["Active"] = ((CheckBox)rRow.FindControl("Active")).Checked;
}
}
As noted I suppose you could drop in a "copy" button, and ONLY persist + save the row index, and then have a paste button - this would allow a cut + paste between any rows, and not be limited to just new rows. (but, that would allow the user quite easy to over-write a existing row - again UI overload from user training point of view.
The above trick is quite slick, since any new rows, any edits are sent back to the database in one simple Update operation. (and the provider is smart - if a row was not touched or changed, then sql update statements are not generated.
This whole trick works due to persisting the table in ViewState. Be warned, if you have a datapager, then you would have to call GridToTable in such navigation, or in fact execute a save command.
Also note how we picked up the .parent.parent (grid row) and again did not bother with teh GV event model. And without a gazilion template stuff, we also saved world poverty in terms of not having to mess with mutiple templates.
In fact, for any grid beyond the above, I use the exact same above approch, but perfer a ListView. The reason is that you can just drag + drop in standard asp.net controls, and you don't have to needless surround them with "item template" which again is too much work and effort.

c# Cannot Convert from string to int

I have a gridview that populates from an SQL table and shows two columns, one comes from an integer data column, the other from an nvarchar. Gridview also has a checkbox column
The gridview populates correctly, and after a subset of rows is selected (via checkbox column) I want to insert the selected rows into another SQL table. When populating the variables for the SQL statement however I get the "Cannot Convert from string to int" error on the value that is populated from an int to begin with.
I have tried writing up convert and parse for this statement but still getting the error:
cmd.Parameters.AddWithValue("#PracticeArea", int.Parse(row.Cells["Id"].Value));
cmd.Parameters.AddWithValue("#PracticeArea", Convert.ToInt32(row.Cells["Id"].Value));
cmd.Parameters.AddWithValue("#PracticeArea", Convert.ToInt32(row.Cells["Id"].Text));
All still show the error on the ["Id"] value.
Any thoughts?
Example of the data that is being populated to the gridview is:
PracticeID PracticeName
1 General Surgical Pathology
2 General Pathology/Basic Science
4 Cardiovascular
6 Cytopathology-GYN
7 Cytopathology-nonGYN
Full button command is:
protected void Bulk_Insert(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if ((row.FindControl("CheckBox1") as CheckBox).Checked)
{
string connectionString = WebConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO ReviewerPractice VALUES(#Reviewer, #PracticeArea)", con))
{
cmd.Parameters.AddWithValue("#Reviewer", ReviewerName.Text);
cmd.Parameters.AddWithValue("#PracticeArea", Convert.ToInt32(row.Cells["Id"].Value));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
Full Gridview control is:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
<asp:BoundField DataField="PracticeName" HeaderText="PracticeName" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button1" Text="Add Practice Areas" OnClick="Bulk_Insert" runat="server" />
Hope this answers (some?) of the questions from all the comments to date.
The problem is that row.Cells[] is an array, so you need to use it like this:
row.Cells[3].Text
And it's better to use the Parameters for sql like this:
cmd.Parameters.Add("#PracticeArea", SqlDbType.Int).Value = Convert.ToInt32(row.Cells[index].Text;

Categories

Resources