Grid View Not Displaying, - c#

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getControls();
}
}
public void getControls()
{
string connn = ConfigurationManager.ConnectionStrings["RiskRegisterDBConnectionString"].ConnectionString;
DataTable ds = DB.GetDataTable("Select * from ControlTable", connn);
// GridView11.DataSource = ds;
GridView11.DataBind();
}
I have tried using AutoGenerationColumn as "true" and "false" both, but I'm not getting the gridview to display in browser while running the program.
<asp:GridView ID="GridView11" runat="server"
AutogenerateColumns="False" Cellpadding="4"
CssClass="auto-style6" DataKeyNames="Control_ID"
DataSourceID="SqlDataSource1"
Forecolor="#333333" Gridlines="None" Width="1124px" >

Try you code say like this:
public void getControls()
{
string strCon =
ConfigurationManager.ConnectionStrings["RiskRegisterDBConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
string strSQL =
#"SELECT * FROM ControlTable";
using (SqlCommand cmd = new SqlCommand(strSQL, conn))
{
DataTable dt = new DataTable();
conn.Open();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}

Related

Pagination gridview on Datasource from serverside

I am assigning DataSource to GridView from server side and apply pagination but it doesn't working. I don't know what i am doing wrong Below is my Code.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
</asp:GridView>
Below is my Server side code.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, City, Country FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}

How to give paging for grid view from data source without databinding

public partial class _Default : System.Web.UI.Page
{
protected void submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data source= LAPTOP-6\\SQLEXPRESS;Initial Catalog=training;integrated Security=true";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Sp_PO";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#date1", TextBox1.Text.ToString());
cmd.Parameters.AddWithValue("#date2", TextBox2.Text.ToString());
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
lblerror.Text = ex.Message.ToString();
}
finally
{
con.Close();
con.Dispose();
}
}
}
How to give paging in some sites they have given bind grid but if i used bind grid here i can't run it on submit button?
protected void reset_Click(object sender, EventArgs e)
{
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
}
protected void save_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data source= LAPTOP-6\\SQLEXPRESS;Initial Catalog=training;integrated Security=true";
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox check = (CheckBox)gvr.FindControl("check");
if (check.Checked)
{
conn.Open();
string data1 = ((Label)gvr.FindControl("pomas_pono")).Text;
string data2 = ((Label)gvr.FindControl("pomas_suppliercode")).Text;
string data3 = ((Label)gvr.FindControl("pomas_pobasicvalue")).Text;
string data4 = ((Label)gvr.FindControl("poitm_itemcode")).Text;
string data5 = ((Label)gvr.FindControl("poitm_order_quantity")).Text;
string data6 = ((Label)gvr.FindControl("poitm_itemvalue")).Text;
string data7 = ((Label)gvr.FindControl("poitm_itemdescription")).Text;
string data8 = ((TextBox)gvr.FindControl("remarks")).Text;
SqlCommand command = new SqlCommand("INSERT INTO po_remarks" + "(pomas_pono,pomas_suppliercode,pomas_pobasicvalue,poitm_itemcode,poitm_order_quantity,poitm_itemvalue,poitm_itemdescription,remarks) VALUES(#pomas_pono,#pomas_suppliercode,#pomas_pobasicvalue,#poitm_itemcode,#poitm_order_quantity,#poitm_itemvalue,#poitm_itemdescription,#remarks)", conn); //generate insert sql using above data
command.Parameters.AddWithValue("#pomas_pono", data1);
command.Parameters.AddWithValue("#pomas_suppliercode", data2);
command.Parameters.AddWithValue("#pomas_pobasicvalue", data3);
command.Parameters.AddWithValue("#poitm_itemcode", data4);
command.Parameters.AddWithValue("#poitm_order_quantity", data5);
command.Parameters.AddWithValue("#poitm_itemvalue", data6);
command.Parameters.AddWithValue("#poitm_itemdescription", data7);
command.Parameters.AddWithValue("#remarks", data8);
command.ExecuteNonQuery();
}
}
conn.Close();
}
protected void cancel_Click(object sender, EventArgs e)
{
Page.Response.Redirect("Default.aspx");
}
The GridView control has a paging option as described here: https://msdn.microsoft.com/en-us/library/aa479347.aspx
<asp:GridView ID=" productsGridView" Runat="server"
DataSourceID="productDataSource" AutoGenerateColumns="False"
AllowSorting="True" BorderWidth="2px" BackColor="White"
GridLines="None" CellPadding="3"
CellSpacing="1" BorderStyle="Ridge" BorderColor="White"
AllowPaging="True" PageSize=50>
Notice the property of: AllowPaging. You can specify the number of records per page using the PageSize property. I think the default PageSize is: 10.
You can also specify the properties programmatically e.g.
GridView1.AllowPaging=true;
GridView1.PageSize=50;
protected void submit_Click(object sender, EventArgs e)
{
BindGrid();
}
protected void BindGrid()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data source= LAPTOP-6\\SQLEXPRESS;Initial Catalog=training;integrated Security=true";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Sp_PO";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}

Textboxes dont update when dropdownlist value is changed ASP.NET

I have four text boxes whose value I need to change based on the selection in a dropdown list. but when I change the value, the textboxes don't update
My codes:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="Employees" DataTextField="FullName" DataValueField="FullName"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="Employees" runat="server"
ConnectionString="<%$ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT [FullName] FROM [Employees] ORDER BY [FirstName]">
</asp:SqlDataSource>
And class file:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string cn = "Data Source=.;Initial Catalog=DBRE ;Integrated Security=True";
SqlConnection scon = new SqlConnection(cn);
SqlCommand scmd = new SqlCommand("Select * from Employees where FullName = '" + DropDownList1.SelectedItem.Value + "'", scon);
SqlDataReader sdr;
try
{
scon.Open();
sdr = scmd.ExecuteReader();
txtName.Text = sdr["FirstName"].ToString();
txtSurname.Text = sdr["LastName"].ToString();
txtDepartment.Text=sdr["Dept"].ToString();
txtCostCentre.Text=sdr["CostCentre"].ToString();
}
catch (Exception ex)
{
}
finally
{
scon.Close();
}
What am i doing wrong here?
May be i think check the exception, Use Reader like or use ExecuteScalar
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
Check this
dynamically filled DropDownList does not retain value on postback ASP.net c#
Try EnableViewState="true"
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" EnableViewState="true" DataSourceID="Employees" DataTextField="FullName" DataValueField="FullName"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Set your dropdownlist with AutoPostBack="true" with the on selected index changed like this:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPNo_selectedChanged" ></asp:DropDownList>
And in your code behind load data into your dropdownlist with the following code:
String conn = System.Configuration.ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(conn);
SqlDataAdapter da = new SqlDataAdapter("select Code from table1", con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
con.Close();
ddl.DataSource = ds.Tables[0];
ddl.DataValueField = "Code";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("-- select --"));
}
}
Now you can bind data on dropdownlist changed with the following code:
protected void ddl_selectedChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
String strQuery = "select description from table1 where Code = #Code";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#Code", ddl.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtbdescription.Text = dr["description"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
where txtbdescription is the id of your textbox.
Hope this will help.
Remove AutoPostBack="True"
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="Employees" DataTextField="FullName" DataValueField="FullName"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
And add if (!ispostback) condition
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!isPostback)
{
string cn = "Data Source=.;Initial Catalog=DBRE ;Integrated Security=True";
SqlConnection scon = new SqlConnection(cn);
SqlCommand scmd = new SqlCommand("Select * from Employees where FullName = '" + DropDownList1.SelectedItem.Value + "'", scon);
SqlDataReader sdr;
try
{
scon.Open();
sdr = scmd.ExecuteReader();
txtName.Text = sdr["FirstName"].ToString();
txtSurname.Text = sdr["LastName"].ToString();
txtDepartment.Text=sdr["Dept"].ToString();
txtCostCentre.Text=sdr["CostCentre"].ToString();
}
catch (Exception ex)
{
}
finally
{
scon.Close();
}
}
}

How do I load data into combobox from database

How do I load data into combobox from database? I want to display the supportID into the combobox in the form. the code I am using is pasted here. I am calling BindData() in the formload. Ia m getting exception as: Cannot bind to the new display member.
Parameter name: newDisplayMember. the code I used is:
public void BindData()
{
SqlConnection con = new SqlConnection(#"server=RSTT2; database = Project ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select supportID from Support";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cbSupportID.DataSource = ds;
cbSupportID.DisplayMember = "supportID";
cbSupportID.ValueMember = "supportID";
cbSupportID.Enabled = true;
cmd.ExecuteNonQuery();
con.Close();
}
The DataSource for your combobox should be a DataTable in this case, try this:
cbSupportID.DataSource = ds.Tables[0];
Or better, you should fill data into a DataTable instead of a DataSet like this:
DataTable dt = new DataTable();
da.Fill(dt);
//...
cbSupportID.DataSource = dt;
public void BindData()
{
SqlConnection con = new SqlConnection(#"server=RSTT2; database = Project ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select supportID from Support";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
cbSupportID.DisplayMember = "supportID";
cbSupportID.ValueMember = "supportID";
cbSupportID.DataSource = ds;
cbSupportID.Enabled = true;
}
I hope this helps.
Follow this example:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace ComboBoxData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string conStr = #"Server =.\SQLEXPRESS2014; Database=NORTHWND; User Id=sa; Password=******";
SqlConnection conn = new SqlConnection(conStr);
DataSet ds = new DataSet();
string getEmpSQL = "SELECT E.LastName FROM dbo.Employees E;";
SqlDataAdapter sda = new SqlDataAdapter(getEmpSQL, conn);
try
{
conn.Open();
sda.Fill(ds);
}catch(SqlException se)
{
MessageBox.Show("An error occured while connecting to database" + se.ToString());
}
finally
{
conn.Close();
}
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = ds.Tables[0].Columns[0].ToString();
}
}
}
CmbDefaultPrinter.DisplayMember = "[table fieldname]";
CmbDefaultPrinter.ValueMember = "[table fieldname]";
CmbDefaultPrinter.DataSource = ds.Tables[0];
CmbDefaultPrinter.Enabled = true;
Mention the Column Name in DataField which you want to load.
and in aspx.cs in page load bind the gridview.
enter code here
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="User_Group" HeaderText="UserName" ItemStyle
Width="150px" />

No output from search button

I have a search button on my web page and it should return the subject name from the DB which are similar to entered search word, but I didnt get any out put when I use the following code... please help me to do it...
this is my C# code
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("server=localhost; database=e-learningsystem; uid=root; password=123;port=3307;");
connection.Open();
string srh = editbox_search.Type;
try
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM subject WHERE Name= LIKE %'" + srh + "'%", connection);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
}
catch
{
}
asp.net code:
<input name="editbox_search" class="editbox_search" id="editbox_search"
maxlength="80" type="text"
style="background-color: #99CCFF; margin-top: 0px; height: 15px;" runat="server"
enableviewstate="True" title="Search Courses:" clientidmode="Inherit"
dir="ltr" visible="True"/>
<asp:Button ID="Button1"
runat="server" Height="26px" Text="Go" Width="32px" />
<asp:GridView ID="GridView1" runat="server" ShowFooter="True"
Caption="<h3 style='background-color:teal;color:white;'>Search Results...</h3>"
BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None">
</asp:GridView>
There is Mistake in Your Query, Correct it as below.
MySqlCommand cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%" + srh + "%'", connection);
First, use a parameterized command to avoid SQL injections. Second, I think the value you are looking for is in the Text property of the input, not the Type property. Lastly, the single quotes go outside the matching characters, i.e., '%searchvalue%'.
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("connection string removed");
connection.Open();
try
{
var cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%#input%'", connection);
cmd.Parameters.Add("#input", editbox_search.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
}
catch (Exception e)
{
// log the exception
}
}
Try this one:
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
MySqlConnection connection = new MySqlConnection("connection string removed");
connection.Open();
try
{
var cmd = new MySqlCommand("SELECT * FROM subject WHERE Name LIKE '%'+#input+'%'", connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#input", editbox_search.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
MySqlDataReader dr = cmd.ExecuteReader();
da.Fill(dr);
GridView1.DataSource = dr;
GridView1.DataBind();
connection.Close();
}
catch (Exception e)
{
// log the exception
}
}
Try this query
SELECT * FROM subject WHERE Name LIKE %'" + srh + "'%

Categories

Resources