gridview won't populate with custom connection string and custom datasource - c#

i've set up an userdefined connection string and now trying to populate a gridview using that,breakpoint shows connection string's fine..also no error,but surprisingly datatable is n't receiving any value..although data exists...what have i done wrong??
Default3.Aspx:
<td colspan="2" align="center">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>
</td>
Default3.Aspx.Cs:
protected void Page_Load(object sender, EventArgs e)
{
string con = OracleDatabase.connection();
String SelectCommand = "select * from EMP";
OracleDataAdapter adp = new OracleDataAdapter(SelectCommand, con);
DataTable dt = new DataTable();
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
/*
OracleDatabase.gridpopulate(SelectCommand, GridView1);
GridView1.DataSource = OracleDatabase.gridpopulate(SelectCommand);
GridView1.DataBind();
*/
//i tried doing this by writting a function At class file also
}
Class file:
public static string connection()
{
oradb = ConfigurationManager.ConnectionStrings["ConnectionString"]
.ConnectionString;
string str = "Data Source="+db+";User ID="+userid+";Password="+password+";";
oradb = String.Concat(oradb, str);
con = new OracleConnection(oradb);
con.Open();
return oradb;
}
/*(function for gridpopulate)
public static void gridpopulate(string SelectCommand,GridView grid1)
{
string con =(ConfigurationManager.ConnectionStrings["ConnectionString"]
.ConnectionString);
con = String.Concat(con, str);
adp = new OracleDataAdapter(SelectCommand,con);
DataTable dt = new DataTable();
adp.Fill(dt);
grid1.DataSource = dt;
grid1.DataBind();
//return dt;
}
*/

Try as per below, instead of returning connection string from function return Oracle Connection object and pass the same to Adapter.
OracleConnection con = OracleDatabase.connection();
public static OracleConnection connection()
{
oradb =ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string str = "Data Source="+db+";User ID="+userid+";Password="+password+";";
oradb = String.Concat(oradb, str);
con = new OracleConnection(oradb);
con.Open();
return con;
}

Related

Asp.Net finding in Code-behind edited values in GridView with autogenerated columns

I am trying to create a user control of a gridview that will be able to display, edit and delete records, being bound to any datatable.
In my user control I have:
<asp:GridView ID="EditableGrid" runat="server" Width="500px" Height="500px" AllowSorting="True"
AutoGenerateColumns = "true"
AutoGenerateDeleteButton ="true" AutoGenerateEditButton="true"
OnRowEditing="EditableGrid_RowEditing"
OnRowCancelingEdit="EditableGrid_RowCancelingEdit"
OnRowUpdating="EditableGrid_RowUpdating"
OnRowDeleting="EditableGrid_RowDeleting"
></asp:GridView>
In my code behind I have:
public void InitGrid(string theconnstr, string thetablename)
{
connstr = theconnstr;
tablename = thetablename;
// Session["edgconnstr"] = connstr;
// Session["edgtablename"] = tablename;
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (!rd.HasRows) return;
fields = new List<EdField>();
for (int i =0; i < rd.FieldCount; i++)
{
fields.Add(new EdField(rd.GetName(i), rd.GetDataTypeName(i)));
}
}
}
con.Close();
}
public void Bind()
{
// connstr = (String)Session["edgconnstr"];
// tablename = (String)Session["edgtablename"];
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
EditableGrid.DataSource = dt;
EditableGrid.DataBind();
EditableGrid.Visible = true;
}
}
}
con.Close();
}
protected void EditableGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
EditableGrid.EditIndex = e.NewEditIndex;
Bind();
}
protected void EditableGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EditableGrid.EditIndex = -1;
Bind();
}
protected void EditableGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
Now I have tried with no success to find the new values of the edited row in the EditableGrid_RowUpdating event handler. I just do not have access to the textboxes, and therefore I cannot run the query to update the old values to the new value. Is what I want to achieve even possible?
Use the e.NewValues Collection.
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int tx = Convert.ToInt32(e.NewValues[0]);
}

DataTable with Rows will not bind to Gridview

I'm trying to build a simple page that will allow for bulk SQL Searches using a text area. The textbox is split on each new line and each line taken as a parameter to query. The resulting row is then added to a DataTable.
There isn't a problem with the query and the DataTable is built and returned as I expected when checked through debug mode. The only problem is when I attempt to bind the DataTable to the gridview , the gridview is left without rows.
I have been scratching my head at this for a hwile now and cannot figure out why the DataTable will not bind. The column names all match up but the actual table in result is unnamed. Is this an issue?
Here's the code.
ASPX:
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="SIM NUMBER" HeaderText="SIM NUMBER" />
<asp:BoundField DataField="Voice" HeaderText="Voice" />
<asp:BoundField DataField="IMSI" HeaderText="IMSI" />
<asp:BoundField DataField="Tariff" HeaderText="Tariff" />
<asp:BoundField DataField="Contract Start" HeaderText="Contract Start" />
<asp:BoundField DataField="Supplier" HeaderText="Supplier" />
</Columns>
</asp:GridView>
And the C# Code:
public partial class Query : System.Web.UI.Page
{
protected static string numbers = "";
protected static string number;
protected static DataTable result = new DataTable();
protected static string simNumber;
protected static string voice;
protected static string IMSI;
protected static string tariff;
protected static string contractStart;
protected static string supplier;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
result.Reset();
result.Columns.Add("SIM NUMBER", typeof(string));
result.Columns.Add("Voice", typeof(string));
result.Columns.Add("IMSI", typeof(string));
result.Columns.Add("Tariff", typeof(string));
result.Columns.Add("Contract Start", typeof(string));
result.Columns.Add("Supplier", typeof(string));
numbers = TextArea1.Value.ToString();
search();
GridView1.DataSource = result;
GridView1.DataBind();
}
protected static void search()
{
string[] split = numbers.Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (string line in split)
{
if (line == string.Empty)
continue;
number = line;
getSupplierInfo();
}
}
protected static void getSupplierInfo()
{
DataTable DT = new DataTable();
using (SqlConnection conn = new SqlConnection(connections.supplierInfo()))
{
string sql = " SELECT * FROM UnionSuppliers WHERE SIM_NUMBER LIKE #parameter ";
conn.Open();
using (SqlCommand select = new SqlCommand
{
CommandType = CommandType.Text,
CommandTimeout = 300,
CommandText = sql,
Connection = conn
})
{
select.Parameters.AddWithValue("#parameter", number);
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter.SelectCommand = select;
adapter.Fill(ds);
DT = ds.Tables[0];
}
}
foreach (DataRow dr in DT.Rows)
{
simNumber = dr["SIM_NUMBER"].ToString();
voice = dr["Voice"].ToString();
IMSI = dr["IMSI"].ToString();
tariff = dr["Tariff"].ToString();
contractStart = dr["Contract_start"].ToString();
supplier = dr["Supplier"].ToString();
addRow();
}
}
protected static void addRow()
{
DataRow simResult = result.NewRow();
simResult["SIM Number"] = simNumber;
simResult["Voice"] = voice;
simResult["IMSI"] = IMSI;
simResult["Tariff"] = tariff;
simResult["Contract Start"] = contractStart;
simResult["Supplier"] = supplier;
result.Rows.Add(simResult);
}
}
Any help would be very much appreciated. I'm sure its something really simple that i'm missing.
Thanks
Try changing:
AutoGenerateColumns="false"
to:
AutoGenerateColumns="true"
I Think you can try like this in aspx file
<Columns>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Your_Field_Name") %>'></asp:Label>
</ItemTemplate>
</Columns>
and in cs file just fit below code
DataTable DT = new DataTable();
using (SqlConnection conn = new SqlConnection(connections.supplierInfo()))
{
string sql = " SELECT * FROM UnionSuppliers WHERE SIM_NUMBER LIKE #parameter ";
conn.Open();
using (SqlCommand select = new SqlCommand
{
CommandType = CommandType.Text,
CommandTimeout = 300,
CommandText = sql,
Connection = conn
})
{
select.Parameters.AddWithValue("#parameter", number);
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter.SelectCommand = select;
adapter.Fill(ds);
DT = ds.Tables[0];
}
}
And now bind your Datatable to Grid View.
GridView1.DataSource = DT;
GridView1.DataBind();

Dynamically Binded Dropdownlist always taking first value when get by ddl.SelectedValue

I have a dynamically bind dropdownlist from which i want insert selected value in a table. But when I submit the form it is taking the very first value of dropdownlist not the selected value and inserts the first value of the dropdownlist.
Here is my code
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
protected void btnStdRegisterSubmit_Click(object sender, EventArgs e)
{
string dateOfBirth = txtStdDOBYear.Text+"-"+ddlStdDOBMonth.SelectedValue + "-"+txtStdDOBDate.Text;
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlInsertStd = "Insert into tbl_studentRegistration (firstName,surname,studentUsername,studentPassword,studentDOB,studentGender,studentMobile,class) values(#firstName,#surname,#studentUsername,#studentPassword,#studentDOB,#studentGender,#studentMobile,#class)";
conn.Open();
SqlCommand cmdInsertStd = new SqlCommand(sqlInsertStd, conn);
cmdInsertStd.Parameters.AddWithValue("#firstName", txtStdFirstName.Text);
cmdInsertStd.Parameters.AddWithValue("#surname", txtStdSurname.Text);
cmdInsertStd.Parameters.AddWithValue("#studentUsername", txtStdUsername.Text);
cmdInsertStd.Parameters.AddWithValue("#studentPassword", txtStdPassword.Text);
cmdInsertStd.Parameters.AddWithValue("#studentDOB", DateTime.Parse(dateOfBirth).ToString("yyyy-MM-dd"));
cmdInsertStd.Parameters.AddWithValue("#studentGender", ddlStdGender.SelectedValue.ToString());
cmdInsertStd.Parameters.AddWithValue("#studentMobile", txtStdMobile.Text);
cmdInsertStd.Parameters.AddWithValue("#class", ddlClass.SelectedValue);
cmdInsertStd.ExecuteNonQuery();
conn.Close();
txtStdFirstName.Text = "";
txtStdSurname.Text = "";
txtStdUsername.Text = "";
ddlClass.SelectedValue = "";
txtStdPassword.Text = "";
txtStdConfirmPassword.Text = "";
ddlStdDOBMonth.SelectedValue = "";
txtStdDOBDate.Text = "";
txtStdDOBYear.Text = "";
ddlStdGender.SelectedValue = "";
txtStdMobile.Text = "";
Response.Redirect("~/index.aspx");
}
}
Please help I am new to asp.net
Problem : You are adding the items into DropDownList for every Page request as your code added in Page_Load EventHandler. so the DropDownList always contain the first item as selectedItem even though you selected different item.
Solution: You need to append the items into DropDownList only when page is Loaded but not on every PostBack request.
You can use Page.IsPostBack to identify wether page request is PostBack request or not.
Try This:
if(!Page.IsPostBack)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as
classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
Page_Load executes every time the page posts back, such as when you click your submit button. You should put your using stateme3nt in a
conditional:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
using (SqlConnection conn = new SqlConnection(connection.getConnection()))
{
string sqlGetClass = "select pk_classID,brachName+'-'+classYear as classInfo from tbl_studentClass";
SqlCommand cmdGetClass = new SqlCommand(sqlGetClass, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdGetClass);
DataSet ds = new DataSet();
da.Fill(ds);
ddlClass.DataSource = ds;
ddlClass.DataTextField = "classInfo";
ddlClass.DataValueField = "pk_classID";
ddlClass.DataBind();
ddlClass.Items.Insert(0, new ListItem("--SELECT--", ""));
conn.Close();
}
}
}
So that your list is not repopulated every time you click your submiit button.
(you should consider putting the list population code in a separate method)

Gridview display

I dont know what it is but i'm having all sorts of issues with this gridview. Below is the code but the issues is the grid is not displaying. Visibility is set to true and the query does return results. So I'm asking for another set of eyes to point out what went wrong here.
Thank you
protected void btnDisplay_Click(object sender, EventArgs e)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\levels.mdb";
DataSet ds;
using (OleDbConnection myConnString = new OleDbConnection())
{
myConnString.ConnectionString = connString;
using (OleDbCommand selectCommand = new OleDbCommand())
{
selectCommand.CommandText = "select * from tblTest";
selectCommand.Connection = myConnString;
myConnString.Open();
using(OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = selectCommand;
ds = new DataSet();
da.Fill(ds, "test");
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}//end click event
and the gridview
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
or
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
data source should have been:
GridView1.DataSource = ds.Tables["test"];
GridView1.DataBind();

How to bind a drop-down control to a data source in ASP.NET

I am new to C#.
I have a project to create an HR system and I created a page to add employees but the supervisor asked me to create a drop down list that displays the department when adding a new employee.
I don't know how to start and what I should do first. I already added a drop down list from the tools but I don't know how to choose the data source and the name and value of it. Should I choose the department table or the employee table?
public partial class _Default : Page
{
private String strcon = ConfigurationManager.ConnectionStrings["hr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
bindgrideview();
}
protected void bindgrideview()
{
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "SELECT F_name , L_name , salary FROM Employee ";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(ADDCmd);
adapter.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
string F_name = TextBox1.Text;
string L_name = TextBox2.Text;
int status = 1;
string salarystr = TextBox3.Text.ToString();
int salary = Int32.Parse(salarystr);
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "ADDEMP";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
ADDCmd.CommandType = CommandType.StoredProcedure;
ADDCmd.Parameters.AddWithValue("#F_name", F_name);
ADDCmd.Parameters.AddWithValue("#L_name", L_name);
ADDCmd.Parameters.AddWithValue("#status", status);
ADDCmd.Parameters.AddWithValue("#salary", salary);
ADDCmd.ExecuteNonQuery();
bindgrideview();
TextBox1.Text = "";
TextBox2.Text = "";
}
And this is a screen shot of my page:
http://store2.up-00.com/Nov12/YXb11858.png
this is the final code there is no error but the dropdown list have no item :(
public partial class _Default : Page
{
private String strcon = ConfigurationManager.ConnectionStrings["hr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
bindgrideview();
}
protected void bindgrideview()
{
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "SELECT F_name , L_name , salary FROM Employee ";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(ADDCmd);
adapter.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
string F_name = TextBox1.Text;
string L_name = TextBox2.Text;
int status = 1;
string salarystr = TextBox3.Text.ToString();
int salary = Int32.Parse(salarystr);
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "ADDEMP";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
ADDCmd.CommandType = CommandType.StoredProcedure;
ADDCmd.Parameters.AddWithValue("#F_name", F_name);
ADDCmd.Parameters.AddWithValue("#L_name", L_name);
ADDCmd.Parameters.AddWithValue("#status", status);
ADDCmd.Parameters.AddWithValue("#salary", salary);
ADDCmd.ExecuteNonQuery();
bindgrideview();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
protected void bindDepartments()
{
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "SELECT ID,department_name FROM Department ";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(ADDCmd);
adapter.Fill(table);
DropDownList1.DataSource = table;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "department_name";
DropDownList1.DataBind();
}
}
As your code works for retrieving Employees Info. from database, you will retrieve the Departments info. from your Departments table.
protected void bindDepartments()
{
SqlConnection strcon1 = new SqlConnection(strcon);
strcon1.Open();
string ADDStr = "SELECT DepartmentId,DepartmentName FROM Departments ";
SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(ADDCmd);
adapter.Fill(table);
ddlDepartments.DataSource = table;
ddlDepartments.DataValueField = "DepartmentId"; //The Value of the DropDownList, to get it you should call ddlDepartments.SelectedValue;
ddlDepartments.DataTextField = "DepartmentName"; //The Name shown of the DropDownList.
ddlDepartments.DataBind();
}

Categories