JavaScript to select all checkboxes in GridView
Link for all dot net and sql server video tutorial playlists
http://www.youtube.com/user/kudvenkat/playlists
Link for slides, code samples and text version of the video
http://csharp-video-tutorials.blogspot.com/2015/03/javascript-to-select-all-checkboxes-in.html
Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.
https://www.youtube.com/channel/UC7sEwIXM_YfAMyonQCrGfWA/?sub_confirmation=1
If the checkbox in the header is checked, all the checkboxes in the GridView should be checked. If we uncheck the checkbox in the header, all the checkboxes in the GridView should be unchecked. When Delete Selected button is clicked the rows that have the checkboxes checked should be deleted.
We will continue with the example that we worked with in Part 2 of JavaScript with ASP.NET tutorial.
Add a TemplateField to the GridView with checkbox in HeaderTemplate and ItemTemplate. At this point the HTML of the GridView should be as shown below. Notice the checkboxes in the first TemplateField.
[asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1"
onrowdatabound="GridView1_RowDataBound"]
[Columns]
[asp:TemplateField]
[ItemTemplate]
[asp:CheckBox ID="CheckBox1" runat="server" /]
[/ItemTemplate]
[HeaderTemplate]
[asp:CheckBox ID="checkboxSelectAll" runat="server" /]
[/HeaderTemplate]
[/asp:TemplateField]
[asp:TemplateField ShowHeader="False"]
[ItemTemplate]
[asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"][/asp:LinkButton]
[/ItemTemplate]
[/asp:TemplateField]
[asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" /]
[asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /]
[asp:BoundField DataField="Gender" HeaderText="Gender"
SortExpression="Gender" /]
[/Columns]
[/asp:GridView]
Include the following 2 JavaScript functions on the page
[script type="text/javascript" language="javascript"]
function HeaderCheckBoxClick(checkbox)
{
var gridView = document.getElementById("GridView1");
for (i = 1; i [ gridView.rows.length; i++)
{
gridView.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = checkbox.checked;
}
}
function ChildCheckBoxClick(checkbox)
{
var atleastOneCheckBoxUnchecked = false;
var gridView = document.getElementById("GridView1");
for (i = 1; i [ gridView.rows.length; i++)
{
if (gridView.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == false)
{
atleastOneCheckBoxUnchecked = true;
break;
}
}
gridView.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = !atleastOneCheckBoxUnchecked;
}
[/script]
Associate HeaderCheckBoxClick() JavaScript function with onclick event of the checkbox in the HeaderTemplate.
Associate ChildCheckBoxClick() JavaScript function with onclick event of the checkbox in the ItemTemplate
This is all the code that is required for implementing select/deselect all checkboxes in gridview.
Now let's see how to delete all the selected rows at once.
Include a HeaderTemplate in the TemplateField that has the Delete LinkButton. Place a LinkButton inside the HeaderTemplate.
1. Remove the CommandName attribute
2. Set Text="Delete Selected"
3. Set ID="lbDeleteAll"
4. Set OnClick="lbDeleteAll_Click"
At the moment ID column in the GridView is a BoundField. Convert it to TemplateField.
Include the following 2 functions in the code-behind file.
private void Delete(string employeeIDs)
{
string cs = ConfigurationManager.ConnectionStrings["SampleDBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("spDeleteEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("@IDs", employeeIDs);
cmd.Parameters.Add(parameter);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
protected void lbDeleteAll_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (GridViewRow gr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("CheckBox1");
if (cb.Checked)
{
sb.Append(((Label)gr.FindControl("Label1")).Text + ",");
}
}
sb.Remove(sb.ToString().LastIndexOf(","), 1);
Delete(sb.ToString());
GridView1.DataBind();
}
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «JavaScript to select all checkboxes in GridView», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.