I have a GridView that is populated from an SqlDataSource with specific values.
How would I add a default row to the top of myGridView?
And I want the the default row to have text 'All'
<asp:GridView ID="gvPoints"
runat="server"
DataSourceID="SqlDataSource_userPoints"
AllowPaging="True"
AutoGenerateColumns="False"
DataKeyNames="id_point,title"
BorderWidth="0px"
Width="100%"
GridLines="None">
<Columns>
<asp:ButtonField
CommandName="selectedPoint"
DataTextField="title"
ButtonType="Link" />
</Columns>
<RowStyle HorizontalAlign="Left"></RowStyle>
</asp:GridView>
<asp:SqlDataSource
ID="SqlDataSource_userPoints"
runat="server"
ConnectionString='<%$ ConnectionStrings:TipTourConnectionString %>'
SelectCommand ="SELECT
id_point,
title,
body
FROM tt_point
WHERE id_user = #id_user">
<SelectParameters>
<asp:QueryStringParameter
QueryStringField="id_user"
DefaultValue="0"
Name="id_user">
</asp:QueryStringParameter>
</SelectParameters>
</asp:SqlDataSource>
I think the easiest way in this scenario would be to add it with the SQL statement.
This assumes id_point is a numeric field. If not, remove the convert function
SELECT 'All' AS id_point, 'All' AS title, 'All' AS body
UNION
SELECT CONVERT(varchar, id_point), title, body FROM tt_point WHERE id_user = #id_user
Replace This
<asp:ButtonField CommandName="selectedPoint" DataTextField="title" ButtonType="Link" />
with this
<asp:ButtonField CommandName="selectedPoint" DataTextField="title" ButtonType="Link" HeaderText="All" />
I added HeaderText="All" to your ButtonField
Make sure in your gridview this is there ShowHeader="true"
If you want to add 2 rows bind your gridview like this
strcon = "data source=.\\SQLEXPRESS;database=testDB;trusted_Connection=yes";
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT id_point,title,body FROM tt_point WHERE id_user = #id_user", connection);
string userid = "0";
command.Parameters.AddWithValue("#id_user", userid);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
DataRow dr = dt.NewRow();
dr["id_point"] = "All";
dr["title"] = "All";
dr["body"] = "All";
dt.Rows.InsertAt(dr, 0);
DataRow dr1 = dt.NewRow();
dr1["id_point"] = "All";
dr1["title"] = "All";
dr1["body"] = "All";
dt.Rows.InsertAt(dr1, 1);
gvPoints.DataSource = dt;
gvPoints.DataBind();
}
call this method on page load like this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridData();
}
}
Here in strcon database name is testDB replace with your databasename
Remove this from gridview DataSourceID="SqlDataSource_userPoints"
Related
I have a gridview set in ASP.Net that has a name and a checkbox.
<h4>Current Instructor</h4>
<div class="hide-overflow">
<asp:GridView runat="server" ID="GridViewInstructor" DataSourceID="SqlDataSourceInstructor" AutoGenerateColumns="false" CssClass="table table-bordered table-striped" ShowHeader="false" EmptyDataText="No Instructor associated to class." DataKeyNames="Instructor">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CBInstructorPrimary" runat="server" Checked='<%#Eval("Primary")%>' OnCheckedChanged="PrimaryUpdate" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="InstructorName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="SqlDataSourceInstructor" DataSourceMode="DataReader" ConnectionString="<%$ ConnectionStrings:HRAgriConnectionString %>"
SelectCommand="
SELECT a.Primary, a.ClassID, a.Instructor, b.LName + ', ' + b.FName as InstructorName
FROM tblClass a
LEFT JOIN tblUser b
ON a.Instructor = b.UserName
WHERE a.ClassID = #classID
ORDER BY a.Primary DESC">
<SelectParameters>
<asp:QueryStringParameter Name="classID" QueryStringField="cid" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</div>
This makes a gridview table that looks like
my c# code behind looks like this
protected void PrimaryUpdate(object sender, EventArgs e)
{
//CheckBox activeCheckBox = sender as CheckBox;
//foreach (GridViewRow rw in GridViewInstructor.Rows)
//{
// CheckBox chkBx = (CheckBox)rw.FindControl("CBInstructorPrimary");
// if (chkBx != activeCheckBox)
// {
// chkBx.Checked = false;
// }
// else
// {
// chkBx.Checked = true;
// }
//}
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "UPDATE tblClass SET [Primary] = #Primary WHERE classID=#classID and Instructor = #InstructorName";
cmd.Connection = con;
con.Open();
foreach (GridViewRow row in GridViewInstructor.Rows)
{
//Get Instructor Name.
string InstructorName = row.Cells[0].Text;
//Get the Class Id from the DataKey property.
classID = Request.QueryString["cid"];
//Get the checked value of the CheckBox.
bool Primary = (row.FindControl("CBInstructorPrimary") as CheckBox).Checked;
//Save to database
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#InstructorName", InstructorName);
cmd.Parameters.AddWithValue("#classID", classID);
cmd.Parameters.AddWithValue("#Primary", Primary);
cmd.ExecuteNonQuery();
}
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
The outcome should be if you check another checkbox it will update the Primary field (which is a bit field) to 1 if checked and all others in that group will be set to 0. And only 1 checkbox can be checked at a time. I know I have commented out the top part for now. I just haven't been able to figure out how to get this working.
All I want to do is when A user clicks on "See more" button on gridview, He will get all the columns of the row button clicked on detailView1.. But I dont know where Im going wrong. Im working on C# asp.net
Can anyone help? Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
DetailsView1.Visible = false;
SqlCommand cmd1 = new SqlCommand("SELECT cars.carid, cars.make, cars.model, cars.condition, cars.amount, img.img FROM cars INNER JOIN img ON cars.carid = img.carid ", con);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button2_Clicked(object sender, EventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
foreach (GridViewRow row in this.GridView1.Rows)
{
Label lblshow = (Label)GridView1.Rows[row.RowIndex].FindControl("carid");
SqlCommand cmd1 = new SqlCommand("Select * from cars where carid='" + lblshow.Text + "'", con);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
DetailsView1.DataSource = dt;
DetailsView1.DataBind();
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" Width="1000px" AllowPaging="True" PageSize="8" CssClass="Grid" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle><PagerStyle CssClass="pgr"></PagerStyle>
<Columns>
<asp:TemplateField>
<HeaderTemplate>Select</HeaderTemplate>
<ItemTemplate>
<asp:Button runat="server" Text="See more" OnClick="Button2_Clicked" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Image</HeaderTemplate>
<ItemTemplate>
<img src='data:image/jpg;base64,<%# Eval("img") != System.DBNull.Value ? Convert.ToBase64String((byte[])Eval("img")) : string.Empty %>' alt="image" height="100" width="150"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
IsPostback on the page load event. Hope your problem get resolved.
I am working with Asp.Net C# and want to take the id of the row with a checkbox from the GridView.
With the code above if is checked the only think i am getting with debug is:
chk: {Text = "" Checked = false}
What i am doing wrong and how i can fix this?
<!-- language: lang-css -->
protected void Page_Load(object sender, EventArgs e)
{
string query = "SELECT * FROM routedoc WHERE Recipient=#user ";
string user = Session["user"].ToString();
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#user", user);
con.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
if(!IsPostBack)
{
BindDropDown();
}
}
private void BindDropDown()
{
string user = Session["user"].ToString();
using (MySqlConnection con2 = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString))
{
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT RouteNo,sender FROM routedoc WHERE Recipient = #user ", con2);
adp.SelectCommand.Parameters.AddWithValue("?user", user);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "sender";
DropDownList1.DataValueField = "RouteNo";
DropDownList1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// Response.Write(GridView1.SelectedRow.Cells[1].Text);
foreach(GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("box") as CheckBox ;
if (chk.Checked)
{
var id = row.FindControl("RouteNo") as Label;
Response.Write(id.Text);
}
}
}
routedoc.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="routedoc.aspx.cs" Inherits="WebApplication2.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>page 2<asp:DropDownList ID="DropDownList1" runat="server" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" Width="136px" >
</asp:DropDownList>
</h1>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Recipient,DocHandle,Sender" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="RouteNo" HeaderText="RouteNo" InsertVisible="False" SortExpression="RouteNo" />
<asp:BoundField DataField="Recipient" HeaderText="Recipient" ReadOnly="True" SortExpression="Recipient" />
<asp:BoundField DataField="DocHandle" HeaderText="DocHandle" ReadOnly="True" SortExpression="DocHandle" />
<asp:BoundField DataField="Sender" HeaderText="Sender" ReadOnly="True" SortExpression="Sender" />
<asp:BoundField DataField="TermNo" HeaderText="TermNo" SortExpression="TermNo" />
<asp:BoundField DataField="SentDate" HeaderText="SentDate" SortExpression="SentDate" />
<asp:BoundField DataField="DueDate" HeaderText="DueDate" SortExpression="DueDate" />
<asp:BoundField DataField="SentTime" HeaderText="SentTime" SortExpression="SentTime" />
<asp:BoundField DataField="DueTime" HeaderText="DueTime" SortExpression="DueTime" />
<asp:BoundField DataField="Action" HeaderText="Action" SortExpression="Action" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="BUDate" HeaderText="BUDate" SortExpression="BUDate" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate><asp:CheckBox ID="Box" runat="server"/>
</ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:imagingConnectionString %>" ProviderName="<%$ ConnectionStrings:imagingConnectionString.ProviderName %>" SelectCommand="SELECT * FROM routedoc "></asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Height="43px" OnClick="Button1_Click" Text="DELETE" Width="109px" />
</form>
</body>
</html>
This is caused by the fact that you always bind your GridView1 with data,
even on post-back. This is causing that all check box-es remain unchecked.
Remove grid loading if you are in post-back, and it should work fine.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string query = "SELECT * FROM routedoc WHERE Recipient=#user ";
string user = Session["user"].ToString();
MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["imagingConnectionString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#user", user);
con.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
BindDropDown();
}
}
If you, however, need to load grid even in post-back, I will tell you a fix for that.
Whenever you bind a data to a data control in Page_Load event, please consider using Page.IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// bind data
}
}
This is because, when you click a button, your page will be still refreshed, which means you will bind the same data to gridview again, resulting in unchecked checkboxes. You can check whether the page is loaded by a button click (Page.IsPostBack) or the page is loaded the first time (!Page.IsPostBack), and do your data binding accordingly.
Hope this makes sense!
I have a asp.net form displaying the user details from an Oracle database, using a grid-view. I even managed to get a check-box field in the grid-view using the following template..
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chck"/>
</ItemTemplate>
</asp:TemplateField>
I want the admin to be able to select multiple entries using the check-boxes and perform a certain action on them. I tried using, for the delete operation, the following
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (Convert.ToBoolean(GridView1.Rows[i].Cells[1].Value == true))
GridView1.Rows.RemoveAt[i];
}
However, this shows an error. Apparently, each check-box on each row must have its own unique index. How do I get to it?
Any sort of help will be appreciated. Thanx :)
You need to find control inside your gridview row using findControl
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox cb1 = (CheckBox)GridView1.Rows[i].FindControls("chck");
if(cb1.Checked)
GridView1.Rows.RemoveAt[i];
}
Use find control to get checkboxes:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chck = (CheckBox)GridView1.Rows[i].FindControl("chck");
if (chck != null)
{
if (chck.Checked)
{
GridView1.Rows.RemoveAt[i];
}
}
}
This is Aspx FIle :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
Font-Names="Arial" GridLines="Vertical" Width="40%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
</asp:GridView>
This is CS File :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
string constr = #"Server=.\SQLEXPRESS;Database=TestDB;uid=waqas;pwd=sql;";
string query = #"SELECT CategoryID, CategoryName, Approved FROM Categories";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkStatus.NamingContainer;
string cid = row.Cells[1].Text;
bool status = chkStatus.Checked;
string constr = #"Server=.\SQLEXPRESS;Database=TestDB;uid=waqas;pwd=sql;";
string query = "UPDATE Categories SET Approved = #Approved WHERE CategoryID = #CategoryID";
SqlConnection con = new SqlConnection(constr);
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("#Approved", SqlDbType.Bit).Value = status;
com.Parameters.Add("#CategoryID", SqlDbType.Int).Value = cid;
con.Open();
com.ExecuteNonQuery();
con.Close();
LoadData();
}
I have an access DB (.mdb) named: Programs, with one table named: Data. By using the DataGridView I present the data from the table Data. I want to delete a row from the DataGridView and from the DB during runtime. Does anyone know how to do that (using C#)?
Another question I have is, who can i run queries on my DB?
thanks!
Very simple.
I suppose in your datagrid you have a check box by choosing which you will be able to choose the rows that you want to delete. And assuming you have a submit button, so after choosing the rows click on the submit button. In the button's click event call the Delete query say delete from tblname where id = #id [#id is the id that will be passed from your grid]
After that just populate the grid e.g. select * from tblname
e.g.
Aspx code
<asp:GridView runat="server" ID="gvTest" Width="100%" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="5%">
<ItemTemplate>
<asp:CheckBox ID="chkDel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="RegID" DataField="RegID" ItemStyle-Width="10%">
<ItemStyle HorizontalAlign="Left"/>
</asp:BoundField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="22%" ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Width="100%" Text= '<%# DataBinder.Eval(Container.DataItem, "UserName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click"></asp:Button>
Submit button cilck event's code
protected void btnSubmit_Click(object sender, EventArgs e)
{
for (int count = 0; count < gvTest.Rows.Count; count++ )
{
CheckBox chkSelect = (CheckBox)gvTest.Rows[count].FindControl("chkDel");
if (chkSelect != null)
{
if (chkSelect.Checked == true)
{
//Receiveing RegID from the GridView
int RegID = Int32.Parse((gvTest.Rows[count].Cells[1].Text).ToString());
object result = DeleteRecord(RegID); //DeleteRecord Function will delete the record
}
}
}
PopulateGrid(); //PopulateGrid Function will again populate the grid
}
public void DeleteRecord(int RegId)
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlConnection connection = new SqlConnection(#connectionPath);
command = "delete from tblname where id = " + RegId
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(command, connection);
cmd.ExecuteNonQuery();
}
catch (SqlException sqlExcep) {}
finally
{
connection.Close();
}
}
public void PopulateGrid()
{
DataTable dt = new DataTable();
dt = GetRecord();
if(dt !=null && dt.rows.count>0)
{
gvTest.DataSource = dt;
gvTest.DataBind();
}
}
public DataTable GetRecord()
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlConnection connection = new SqlConnection(#connectionPath);
command = "Select * from tblname" ;
connection.Open();
SqlCommand sqlCom = new SqlCommand(command, connection);
adapter.SelectCommand = sqlCom;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
Hope this makes sense.