I've got a TabContainer control which houses several tabs. Depending on the ActiveIndex property of the TabContainer I would like for a button click to create a Gridview in that tab and bind it to a stored procedure. Currently, the following code works, but there's a lot of code repeated
protected void btnMakeGridView_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
if (TabContainer1.ActiveTabIndex == 0)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spTest0", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(gv);
gv.DataSource = rdr;
gv.DataBind();
}
}
}
else if (TabContainer1.ActiveTabIndex == 1)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spTest1", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(gv);
gv.DataSource = rdr;
gv.DataBind();
}
}
}
else if (TabContainer1.ActiveTabIndex == 2)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spTest2", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(gv);
gv.DataSource = rdr;
gv.DataBind();
}
}
}
else
{
Label1.Text = "You must select a tab to create the GridView in";
}
}
As you can see depending on the ActiveIndex of the TabContainer, a different stored procedure should be created inside each TabPanel. In my example I'm only working with one database so I don't have to worry about passing the connection string as a parameter for a database to connect to. At first blush I had added something like
//pass in the connection string, the stored procedure name and the ActiveTabIndex
public static void DataAccess(string connectionString,string spName, int activeTabIndex)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(spName, con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
gv.DataSource = rdr;
gv.DataBind();
}
}
}
UDPATE: Okay, in the meantime I came up with
public partial class _Default : System.Web.UI.Page
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnMakeGridView_Click(object sender, EventArgs e)
{
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(GetData(cs, "spTest", TabContainer1.ActiveTabIndex));
}
public static GridView GetData(string connectionString,string spName, int activeIndex)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(spName, con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
gv.ID = "gv" + activeIndex.ToString();
gv.DataSource = rdr;
gv.DataBind();
return gv;
}
}
}
}
Related
I have two dropdownlists named ddFatherEmployeeNumber and ddEmployeeFatherName. Now on load event i am populating ddFatherEmployeeNumber from database. Here is the code
private DataTable LoadComboBoxFatherEmployeeNumber()
{
DataTable dtFatherENo = new DataTable();
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, EmployeeNo FROM TableFatherMaster", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
SqlDataReader r = cmd.ExecuteReader();
dtFatherENo.Load(r);
}
}
return dtFatherENo;
}
Load Event code is
if (!IsPostBack)
{
ddFatherEmployeeNumber.DataSource = LoadComboBoxFatherEmployeeNumber();
ddFatherEmployeeNumber.DataTextField = "EmployeeNo";
ddFatherEmployeeNumber.DataValueField = "Id";
ddFatherEmployeeNumber.DataBind();
ddFatherEmployeeNumber.Items.Insert(0, new ListItem("Select Father Employee No", "0"));
}
Here is the .aspx code for ddFatherEmployeeNumber
<div class="col-8">
<asp:DropDownList ID="ddFatherEmployeeNumber" runat="server" class="form-control here" AutoPostBack="True" OnSelectedIndexChanged="ddFatherEmployeeNumber_SelectedIndexChanged"></asp:DropDownList>
</div>
Now i want to populate the ddEmployeeFatherName on the bases of ddFatherEmployeeNumber selected value. I mean when a user select employee number from ddFatherEmployeeNumber list then from database, Name of that employee loads and populate the ddEmployeeFatherName. For that purpose i already write a code on ddFatherEmployeeNumber_SelectedIndexChanged Event. Here is the Code.
protected void ddFatherEmployeeNumber_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddEmployeeFatherName.SelectedIndex == 0)
{
}
else
{
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableFatherMaster WHERE EmployeeNo=#EmployeeNo ", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeNo", ddFatherEmployeeNumber.SelectedValue);
con.Open();
SqlDataReader r = cmd.ExecuteReader();
ddEmployeeFatherName.DataSource = r;
ddEmployeeFatherName.DataBind();
}
}
}
}
Now the problem is, it doesn't loads data into ddEmployeeFatherName.
Here is the picture for clear understanding
Try setting DataTextField and DataValueField properties for ddEmployeeFatherName first, because you're not setting them before using DataBind():
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableFatherMaster WHERE EmployeeNo=#EmployeeNo ", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeNo", ddFatherEmployeeNumber.SelectedValue);
con.Open();
SqlDataReader r = cmd.ExecuteReader();
ddEmployeeFatherName.DataSource = r;
// set text and value fields
ddEmployeeFatherName.DataTextField = "Name";
ddEmployeeFatherName.DataValueField = "Id";
ddEmployeeFatherName.DataBind();
}
}
If the dropdownlist option values are still empty, try loading SqlDataReader contents into DataTable and use it instead:
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableFatherMaster WHERE EmployeeNo=#EmployeeNo ", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeNo", ddFatherEmployeeNumber.SelectedValue);
con.Open();
SqlDataReader r = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(r);
ddEmployeeFatherName.DataSource = dt;
ddEmployeeFatherName.DataTextField = "Name";
ddEmployeeFatherName.DataValueField = "Id";
ddEmployeeFatherName.DataBind();
}
This is neither producing an error nor output. Help me out in this. Here my code is :
public partial class ScoHelpDesk : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
SqlDataAdapter adapt;
DataTable dt;
SqlConnection con2, con3;
SqlCommand cmd, cmd1, cmd2;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData_Sheet();
}
}
protected void InsertData1(object sender, EventArgs e)
{
try
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlserver"].ConnectionString);
TextBox t1 = (TextBox)GridView1.FooterRow.FindControl("TextBox2");
TextBox t2 = (TextBox)GridView1.FooterRow.FindControl("TextBox4");
TextBox t3 = (TextBox)GridView1.FooterRow.FindControl("TextBox6");
TextBox t4 = (TextBox)GridView1.FooterRow.FindControl("TextBox8");
TextBox t5 = (TextBox)GridView1.FooterRow.FindControl("TextBox10");
TextBox t6 = (TextBox)GridView1.FooterRow.FindControl("TextBox12");
cmd = new SqlCommand("insert into tblHelpDesk (Name,Purpose,ContactNo,AlternativeNo,Email,Address) values(#Name,#Purpose,#ContactNo,#AlternativeNo,#Email,#Address)", con);
con.Open();
cmd.Parameters.AddWithValue("#Name", t1.Text);
cmd.Parameters.AddWithValue("#Purpose", t2.Text);
cmd.Parameters.AddWithValue("#ContactNo", t3.Text);
cmd.Parameters.AddWithValue("#AlternativeNo", t4.Text);
cmd.Parameters.AddWithValue("#Email", t5.Text);
cmd.Parameters.AddWithValue("#Address", t6.Text);
cmd.ExecuteNonQuery();
Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
catch (Exception ex)
{ }
}
private void BindData_Sheet()
{
DataTable dt = new DataTable();
using (SqlConnection con2 = new SqlConnection(con.ConnectionString))
{
string strQuery = "SELECT * FROM tblHelpDesk ";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
I want to display records in pivot grid (devexpress). The data will return from Stored Procedure
pivotTest is the name of pivotgrid,I can give the connection String later. But I don't how to bind data to pivot grid.
One more doubt. In which scenario,we should use SqlDataReader and SqlDataAdapter
private void ReportTestForm_Load(object sender, EventArgs e)
{
string cs = "";
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spProcedureTest", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
pivotTest.DataSource = rd;
pivotTest.DataBindings;
}
}
I have a gridview but currently it only sets one header. What I want it to do is add new header beside the other columns at the end of the table based on the number of users.
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView1.UseAccessibleHeader = true;
GridView1.AutoGenerateColumns = false;
int i = 6;
string constr = ConfigurationManager.ConnectionStrings["CMT"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM [user]";
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
GridView1.Columns[6].HeaderText = sdr["user_first_name"].ToString();
break;
}
}
conn.Close();
}
}
}
}
You can add TemplateField columns to the GridView before binding the data. It could be done in the Page_Load event handler:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM [user]";
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
TemplateField field = new TemplateField();
field.HeaderText = sdr["user_first_name"].ToString();
field.HeaderStyle.Width = Unit.Pixel(80);
GridView1.Columns.Add(field);
}
}
conn.Close();
}
}
}
}
I have two query's in C# running in a datagridview, one is to show all data. the other is set to display in the footer. The footer is showing, just not displaying my query.
query one (with footer)
protected void Button2_Click(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.ShowFooter = true;
dg.DataSource = dgl;
dg.DataBind();
cs.Close();
}
**query two(footer query)**
protected void dg_DataBound(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
String totalDonations = Convert.ToString(cmd.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[3].Text = totalDonations;
}
the datagrid shows query one works well, the footer even shows but it has not got any data.
Although you have it working, there are ways to improve it.
In the first method, using statement would manage the connection better:
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customer", con))
{
da.Fill(dt);
}
}
dg.ShowFooter = true;
dg.DataSource = dt;
dg.DataBind();
}
And the second method:
protected void dg_DataBound(object sender, EventArgs e)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
dg.FooterRow.Cells[3].Text = totalDonations;
}
Probably I would use GridView's RowDataBound to write into footer where I can can know the type of row:
protected void dg_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
e.Row.Cells[3].Text = totalDonations;
}
}
EDIT : Here's the markup I have used to test:
<asp:GridView ID="dg" runat="server" AutoGenerateColumns="true" OnDataBound="dg_DataBound" ShowFooter="true">
</asp:GridView>
After hours of problems, I have solved it.
corrected code
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
MySqlCommand cmdtwo = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.DataSource = dgl;
dg.ShowFooter = true;
dg.DataBind();
cs.Close();
cs.Open();
string totalDonations = Convert.ToString(cmdtwo.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[7].Text = "Total £";
dg.FooterRow.Cells[8].Text = totalDonations;
}
although I am sure there is a better way of doing this, if you know please feel free to edit.