how to bind gridview to sqldatasource to our own created form - asp.net

I have a form and 'Add' button. when i click on add then i insert data into database and also i have sqldatasource in which i specify only select,update,delete commands. when i insert data on Add button then i want to refresh and fill the grid automatically.
my sqldatasource id is "sqldatasourceDenter" and i have specified it in my gridview datasourceID="sqldatasourceDenter".
i have tried this
GridView1.DataSourceID = sqldatasourceDenter;
it gives me the error cannot convert sqldatasource to string
i have also defined datasource but it tells both me both datasource, datasourceID cannot be defined.
I actually want to insert data on my 'Add' button then refresh the sqldataSourceDenter to fill the grid.
This is my add button click event function:
..... add_Click(object sender, EventArgs e){
..
.... /* here i have other code*/
.....
else {
string dentername = dname.Text.ToString();
string denteraddress = daddress.Text.ToString();
string dentercontact = dcontact.Text.ToString();
//create sql inset query and take to insert query ftn for execution
string dquery = string.Format("INSERT INTO Denters(D_NIC, D_Name, D_Address, D_Contact) VALUES('{0}','{1}','{2}','{3}')", denternic, dentername, denteraddress, dentercontact);
InsertIntoDB.InsertQuery(dquery);
if (InsertIntoDB.count > 0)
{
gvDenter.DataSourceID = SqlDataSourceDenter;
Response.Write("<script>alert('Denter added successfully')</script>");
InsertIntoDB.count = 0;
ClearDenterFields();
}
}
}
My aspx code is:
<asp:SqlDataSource ID="SqlDataSourceDenter" runat="server" ConnectionString="<%$ ConnectionStrings:VehiclesSystemConnectionString2 %>"
SelectCommand="SELECT [D_NIC], [D_Name], [D_Address], [D_Contact] FROM [Denters]">
</asp:SqlDataSource>
<asp:GridView ID="gvDenter" Visible="False" DataKeyNames="D_NIC" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceDenter" >
</asp:GridView>

You can have something like
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataToGrid();
}
}
protected void BindDataToGrid()
{
string conString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(conString))
{
string myQuery = "SELECT * FROM MYTABLE";
SqlCommand cmd = new SqlCommand(myQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void Add(object sender, EventArgs e)
{
//Insert To DB Code here
}

Related

Fill a grid view by a drop down list

I have a drop down list ; a sqldatasource and a gridview .
I want to fill the grid view by the choice in the drop down list.
How can i implement this fill ?
Thanks
My question is not a duplicate of this Click
because it want to populate a drop down list inside the grid view instead my question is : by a choice of a drop down list , fill a grid view.
EDIT (Because i am in negative rep.) :
What i have tried
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
aspx page
<asp:DropDownList runat="server" ID="drp" AutoPostBack="true" OnSelectedIndexChanged="drp_SelectedIndexChanged"></asp:DropDownList>
<asp:GridView runat="server" ID="grd" AutoGenerateColumns="true"></asp:GridView>
code behind of aspx
protected void drp_SelectedIndexChanged(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
grd = dataSource;
grd.DataBind();
}
Bind grid on selection index change event of dropdown.

Get submit button id for query

I have a master page in witch more then 30 button like (java,asp,php,sql,c,c++,etc...)
and a have a table of questions. All questions are tagged with one subject like asp,java,etc.
I want to get data according to the click button.
How is it possible?
protected void BindRepeaterData()
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * from question", con);
int count = (int)cmd.ExecuteScalar();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
RepDetails.DataSource = ds;
RepDetails.DataBind();
con.Close();
}
(I think one page for one button is not a good idea.)
There are few ways to capture button click inside Data such as Repeater, GridView, ListView.
Easiest way is to use Command event instead of Click event.
<%-- Let say this button is located inside Repeater control.--%>
<asp:Button ID="DoSomethingButton" runat="server" Text="Home"
OnCommand="DoSomethingButton_Command" CommandArgument="<%# Eval("Id") %>" />
// Retrieve e.CommandArgument from code-behind.
protected void DoSomethingButton_Command(object sender, CommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument);
}
If you want the ID of the button itself, you can cast the sender back to the Button and get it's ID.
protected void Button1_Click(object sender, EventArgs e)
{
Button button = sender as Button;
string id = button.ID;
}
If I understand you question correctly you could select field from the table according to button information for example in this way. And you could use same event handler for different buttons. Hope this helps.
protected void Btn1_Click(object sender, EventArgs e)
{
Button button = sender as Button;
string question = readData(button.Text);
//do further actions
}
private string readData(string subject)
{
string question = string.Empty;
using (SqlConnection con = new SqlConnection(/*connection_string*/))
{
using (SqlCommand cmd = new SqlCommand("SELECT question from question_table where subject = #subject", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#subject", subject);
con.Open();
object o = cmd.ExecuteScalar();
if (o != null){
question = o.ToString();
}
con.Close();
}
}
return question;
}

ASP.NET Listview.selectedindex property goes crazy

I'm deleting a single database record from a listview and after deleting I try to navigate in my listview using listView1.selectedindex property, but I have noticed that it highlights the incorrect record (for example I set listView1.selectedindex to 1 but it displays a record which has index 0) . What is wrong? Please help!
protected void deleteButton_Click(object sender, EventArgs e)
{
int id = int.Parse(((Label)ListView1.Items[ListView1.SelectedIndex].FindControl("idLabel")).Text);
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
BindDataFromBaseToListView method looks so:
private void BindDataFromBaseToListView()
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("select * from Employee", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
ListView1.DataSourceID = null;
ListView1.DataSource = dTable;
ListView1.DataBind();
}
conn.Close();
}
Instead of using deleteButton_Click event you could use your ListView's OnItemCommand event to get the selected row values and delete the item that you want like the code below:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int id = 0;
if(int.TryParse((e.Item.FindControl("idLabel") as Label).Text, out id))
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string Sql = "delete from Employee where id = #id";
conn.Open();
using (SqlCommand dCmd = new SqlCommand(Sql, conn))
{
dCmd.Parameters.AddWithValue("#id", id);
dCmd.ExecuteNonQuery();
}
conn.Close();
}
BindDataFromBaseToListView();
}
}
}
And on your control's element will look like this:
<asp:ListView ID="ListView1" runat="server" OnItemCommand="ListView1_ItemCommand" .. >
...
<ItemTemplate>
<asp:Button runat="server" CommandName="delete" Text="Delete" ID="DeleteButton" />
...
Let me know if you still have issue with it.

Paging in Gridview not working 2nd page data not showing data?

my gridview
<div style="margin-left: 280px">
<asp:GridView ID="exportGrdVw" runat="server" BackColor="White"
AllowPaging="True" PageSize="3"
OnPageIndexChanging="exportGrdVw_PageIndexChanging"
onpageindexchanged="exportGrdVw_PageIndexChanged">
</asp:GridView>
</div>
my code
SqlConnection con = new SqlConnection("server=acer-Pc\\Sql;database=MYDB;trusted_connection=yes");
//DataSet ds = new DataSet();
DataTable table = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
da.Fill(table);
BindEmployee();
}
}
public void BindEmployee()
{
exportGrdVw.DataSource = table;
exportGrdVw.DataBind();
}
protected void exportGrdVw_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
exportGrdVw.PageIndex = e.NewPageIndex;
BindEmployee();
}
the problem is gridview is displaying but when i click page 2. 2nd page data is not showing (blank). pls help me to solve this problem.
see that the code is correct or not
Use like below
SqlConnection con = new SqlConnection("server=acer-Pc\\Sql;database=MYDB;trusted_connection=yes");
//DataSet ds = new DataSet();
DataTable table = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployee();
}
}
public void BindEmployee()
{
SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
da.Fill(table);
exportGrdVw.DataSource = table;
exportGrdVw.DataBind();
}
protected void exportGrdVw_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
exportGrdVw.PageIndex = e.NewPageIndex;
BindEmployee();
}
Your datatable gets initialize in every page load so you need to get the datatable
everytime before binding it to grid.
Set your page Index before binding it to grid
So your code should be like this
public void BindEmployee(int newPageIndex = -1)
{
SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
da.Fill(table);
exportGrdVw.PageIndex = newPageIndex;
exportGrdVw.DataSource = table;
exportGrdVw.DataBind();
}
No need to call database on exportGrdVw_PageIndexChanging. Just declare DataTable table as static
You can try this:
GridView1.PageIndex = e.NewPageIndex;
SqlCommand cmd = new SqlCommand("Select * from Emp_Data ORDER BY [ID] DESC", con);
SqlDataAdapter DA1 = new SqlDataAdapter(cmd);
DA1.Fill(DT1);
GridView1.DataSource = DT1;
GridView1.DataBind();

GridView lost sorting after paging?

I got the below code from internet. It is working properly. I have added paging also. When I'm just sorting, it is working properly. When I am changing the page index, the sorting is lost.
Here is the client side code that set a gridview with 20 items per page, using the sort linked to the "GridView1_Sorting" method in the server side code.
Client side
<asp:GridView ID="GridView1" runat="server" DataKeyNames="eno" AutoGenerateColumns="False" PageSize="20" AllowPaging="True" AllowSorting="True" OnSorting="GridView1_Sorting" CellPadding="4">
<Columns>
<asp:TemplateField HeaderText="Employee no" SortExpression="eno">
<ItemTemplate>
<%#Eval("eno")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp name" SortExpression="empname">
<ItemTemplate>
<%#Eval("empname")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary" SortExpression="sal">
<ItemTemplate>
<%#Eval("sal")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And now the server side code:
Server side
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridData();
}
}
void GridData()
{
sqlcmd = new SqlCommand("select * from emp", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["dt"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
private string GVSortDirection
{
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string GetSortDirection()
{
switch (GVSortDirection)
{
case "ASC":
GVSortDirection = "DESC";
break;
//assign new direction as ascending order
case "DESC":
GVSortDirection = "ASC";
break;
}
return GVSortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = (DataTable)Session["dt"];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
string sortDirection = GetSortDirection();
dataView.Sort = e.SortExpression + " " + sortDirection;
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridData();
}
}
When you page, the PageIndexChanging event is called. This in turn runs the GridData() procedure, which sets the data source for the gridview to be a data table containing records from the emp table, with no particular sort order.
What you should do is to take the code that you've written in your GridView1_Sorting event-handler, and include this within the GridData routine, so that whenever the grid is populated with data - whether when the page first loads, when the page index is changed or when the gridview is sorted - the gridview is based on a sorted dataview, rather than an unsorted data table.
The way you are maintaining SortDirection using GetSortDirection, in same fashion maintain SortExpression.
Happy coding!!!
Have a look to this article, may you will get what you want

Resources