I am making an application in asp.net using C# which contains drop down list.Now I don't want to write same code for fetching same data from database.I am try this code but it's not working
protected void Page_Load(object sender, EventArgs e)
{
DataTable DT = sel_obj.select_Dept_Name();
departmentDrop.DataSource = DT;
departmentDrop.DataMember = "Department_Name";
departmentDrop.DataBind();
}
public DataTable select_Dept_Name()
{
module c = new module();
c.DB_Connection();
if (c.con.State == ConnectionState.Open)
{
c.con.Close();
c.con.Open();
}
DataSet DS = new DataSet();
string QRY = "";
QRY = "SELECT Department_Name FROM Department_Master";
SqlDataAdapter DA = new SqlDataAdapter(QRY, c.con);
DA.Fill(DS);
DataTable DT = DS.Tables[0];
return DT;
}
You need to call "DataBind()" function. You need to also make sure that your table contains data to bind with dropdown list.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable DT = sel_obj.select_Dept_Name();
departmentDrop.DataSource = DT ;
departmentDrop.DataTextField = "Department_Name";
departmentDrop.DataValueField = "Department_Name";
departmentDrop.DataBind();
}
}
Related
I have followed method from this SO post to perform search on datagridview
Below is my attempt. I would like to stop querying database with DgvSearch() method on text change, instead use RowFilter.
Within current attempt, datagridview is properly populated from LoadDataParts(), when i start typing in TxtPP_GBC2, i see only column header, no exception is thrown.
GBC column is defined as "INT".
Expected result -> TxtPP_GBC2_TextChanged() will behave same like DgvSearch()
public partial class ProgramPart : Form
{
public SqlConnection Con { get; } = new SqlConnection(#"***");
public string UserDBO;
private DataTable dataTable = new DataTable();
public ProgramPart()
{
InitializeComponent();
LoadDataParts();
}
public void LoadDataParts()
{
string sql3 = "SELECT * FROM Parts";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql3, Con);
sqlDataAdapter.Fill(dataTable);
sqlDataAdapter.Dispose();
dataGridView1n.DataSource = dataTable;
}
private void TxtPP_GBC2_TextChanged(object sender, EventArgs e)
{
//DgvSearch(); //////// DgvSearch() works perferctly
try
{
if(txtPP_GBC2.Text == "")
{
dataTable.Clear();
LoadDataParts();
dataGridView1n.Refresh();
return;
}
(dataGridView1n.DataSource as DataTable).DefaultView.RowFilter = "GBC = '" + Convert.ToInt32(txtPP_GBC2.Text) + "'";
dataGridView1n.Refresh();
}
catch(Exception s)
{
MessageBox.Show(s.ToString());
}
}
private void DgvSearch()
{
string sql3 = "SELECT * FROM Parts WHERE GBC LIKE #GBC2 AND Description LIKE #DES";
Con.Open();
SqlDataAdapter da = new SqlDataAdapter(sql3, Con);
da.SelectCommand.Parameters.AddWithValue("#GBC2", SqlDbType.Int).Value = "%" + txtPP_GBC2.Text + "%";
da.SelectCommand.Parameters.AddWithValue("#DES", SqlDbType.VarChar).Value = "%" + txtPP_Description2.Text + "%";
DataSet ds = new DataSet();
da.Fill(ds, "Parts");
da.Dispose();
dataGridView1n.DataSource = ds;
dataGridView1n.DataMember = "Parts";
Con.Close();
}
}
You can use Convert expression function to convert value of the int column to the string and compare it using such filter:
private DataTable LoadData()
{
var dt = new DataTable();
dt.Columns.Add("C1", typeof(int));
dt.Rows.Add(1);
dt.Rows.Add(11);
dt.Rows.Add(2);
dt.Rows.Add(22);
return dt;
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = LoadData();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
var filter = "";
if (!string.IsNullOrEmpty(textBox1.Text))
filter = $"Convert([C1], System.String) = '{textBox1.Text}'";
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = filter;
}
If for any reason you prefer LIKE operator, you need to change the filter to:
filter = $"Convert([C1], System.String) LIKE '%{textBox1.Text}%'";
I'm trying to load some data from a database, and to filter them using this method.
Now, i want also to show them by pages, especially at the non-filtered part.
I used a DataAdaptor to fill up a dataset table, on which I'm making my filtering.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
OracleConnection con = new OracleConnection(CS);
string query = "select * from table1";
OracleDataAdapter dataAdapter = new OracleDataAdapter(query, con);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "mytbl");
Session["DATASET"] = dataSet;
GridView1.DataSource = from dataRow in dataSet.Tables["mytbl"].AsEnumerable()
orderby dataRow["ID"]
select new guards
{
ID = Convert.ToInt32(dataRow["ID"]),
Nume = dataRow["NUME"].ToString()
};
GridView1.AllowPaging = true;
GridView1.DataBind();
}
You will have to tell ASP.NET how to page. in this case it is .Skip().Take()
I have searched this problem and non of the answers have not solved My problem.
when user types a word a word and clicks a button a SqlDataAdapter searches the database and puts the results to a datatable which populates the gridview.
When enabling the paging in gridview only the first page of gridview shows data !
here is my code. This is where my data table is defined :
private DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Search_Click(object sender, EventArgs e)
{
kcestring.DataSource = #"localhost";
kcestring.InitialCatalog = "KCE";
kcestring.UserID = "sa";
kcestring.Password = "123";
SqlDataAdapter searchadap = newSqlDataAdapter("sp_GetDevicePropByDeviceName2", kcestring.ToString());
searchadap.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter categoryID = new SqlParameter("categoryID", SqlDbType.BigInt);
categoryID.Value = drp_SubCategories.SelectedValue;
searchadap.SelectCommand.Parameters.Add(categoryID);
DataTable dt = new DataTable();
searchadap.Fill(dt);
grv_Device.DataSource = dt;
grv_Device.DataBind();
}
protected void grv_Device_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grv_Device.DataSource = dt;
grv_Device.PageIndex = e.NewPageIndex;
grv_Device.DataBind();
}
Just remove
DataTable dt = new DataTable();
before
searchadap.Fill(dt);
The reason is that you have defined two dt (One global and the other local to the event btn_Search_Click). On the btn_Search_Click event you are filling the local dt. grv_Device_PageIndexChanging event is not getting any rows because its accessing the global variable. Both are different variables.
the answer was to big foe a comment !
this is my page load it contains stuff which is used in other parts of program :
protected void Page_Load(object sender, EventArgs e)
{
btn_Edit.Enabled=false ;
lbl_error.Visible = false;
if (!Convert.ToBoolean(Session["logedin"]))
{
Response.Redirect("Default.aspx");
}
hiddenitems.Visible = false;
if (Page.IsPostBack)
{ btn_Search.Visible = true;
lbtn_advacedsearch.Visible = true;
drp_Property.Visible = true;
txt_pvalue.Visible = true;
Label5.Visible = true;
Label4.Visible = true;
}
img_Logo.Visible = false;
//imgLogo.Src = "pics/Manufacturer_Logo/selectmodel.jpg";
SqlConnectionStringBuilder kcestring = new SqlConnectionStringBuilder();
kcestring.DataSource = #"localhost";
kcestring.InitialCatalog = "KCE";
kcestring.UserID="sa";
kcestring.Password="123";
//kcestring.IntegratedSecurity = true;
SqlDataAdapter empper = new SqlDataAdapter("sp_GetEmployeepermissionsByID", kcestring.ToString());
SqlParameter employeeID = new SqlParameter("employeeID", SqlDbType.BigInt);
employeeID.Value = Session["employeeid"];
empper.SelectCommand.Parameters.Add(employeeID);
empper.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable da = new DataTable();
empper.Fill(da);
}
Use this code inside PageIndexChanging:
{
GridView1.PageIndex = e.NewPageIndex;
SqlCommand cmd = new SqlCommand("Select * from Requseted_movie ORDER BY [ID] DESC", con);
SqlDataAdapter DA1 = new SqlDataAdapter(cmd);
DA1.Fill(DT1);
GridView1.DataSource = DT1;
GridView1.DataBind();
}
I have a textBox and a search button that fills the first Gridview. After that a Second Button Copies the first grid rows in the second grid . After that i should be able to search again in the first grid and attach the other results to the second grid.
But i get an error. Thnx in advance.
Here is my code:
public partial class Grid: System.Web.UI.Page
{
DataTable Dt = new DataTable();
private DataTable Dt1
{
set { ViewState.Add("Dt1", value); }
get { return (DataTable)ViewState["Dt1"]; }
}
private void Fill_grid()
{
string query = "Select * from table " +
" where field1 like '" + TextBox1.Text + "' or filed2 like '" +TextBox1.Text + "'";
SqlConnection cnn = new SqlConnection(...);
SqlCommand cmm = new SqlCommand(query,cnn);
cmm.CommandType = System.Data.CommandType.Text;
SqlDataAdapter MyDataAdapter = new SqlDataAdapter(cmm);
DataSet DS = new DataSet();
cnn.Open();
MyDataAdapter.Fill(DS, "Client");
Dt1 = DS.Tables["klient"];
DataView dv = new DataView(Dt1);
GridView2.DataSource = DS.Tables["klient"].DefaultView;
GridView2.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
Fill_grid();
}
protected void Button1_Click(object sender, EventArgs e)
{
Fill_Second_Grid();
}
private void Fill_Second_Grid()
{
DataRow dr;
foreach (GridViewRow row in GridView2.Rows)
{
dr = Dt.NewRow();
dr["Email"] = row.Cells[0].Text; ;
Dt.Rows.Add(dr);
}
GridView3.DataSource = Dt;
GridView3.DataBind();
}
}
I want to add search functionality to my program. There's a class which has this function:
public DataTable Search()
{
string SQL = "Select * from Customer where " + mField + " like '%" + mValue + "%'";
DataTable dt = new DataTable();
dt = dm.GetData(SQL);
return (dt);
}
There are setter and getter properties for mField and mValue. DM is the object of class DataManagement, which has a method GetData:
public DataTable GetData(string SQL)
{
SqlCommand command = new SqlCommand();
SqlDataAdapter dbAdapter = new SqlDataAdapter();
DataTable DataTable = new DataTable();
command.Connection = clsConnection.GetConnection();
command.CommandText = SQL;
dbAdapter.SelectCommand = command;
dbAdapter.Fill(DataTable);
return (DataTable);
}
The search functionality is currently implemented like this:
private void btnfind_Click(object sender, EventArgs e)
{
//cust is the object of class customer//
if (tbCustName.Text != "")
{
cust.Field="CustName";
cust.Value = tbCustName.Text;
}
else if (tbAddress.Text != "")
{
cust.Value = tbAddress.Text;
cust.Field="Address";
}
else if (tbEmail.Text != "")
{
cust.Value = tbEmail.Text;
cust.Field="Email";
}
else if (tbCell.Text != "")
{
cust.Value = tbCell.Text;
cust.Field = "Cell";
}
DataTable dt = new DataTable();
dt = cust.Search();
dgCustomer.DataSource = dt;
RefreshGrid();
}
private void RefreshGrid()
{
DataTable dt = new DataTable();
dt = cust.GetCustomers();
dgCustomer.DataSource = dt;
}
This is not working. I don't know why. Please help.
Add a DataBind() statement in your RefreshGrid() method to have your new results actually shown on the Grid.
private void RefreshGrid()
{
DataTable dt = cust.GetCustomers();
dgCustomer.DataSource = dt;
dgCustomer.DataBind();
}
Consider modifying your other method as well:
Your ad-hoc SQL has a SQL injection vulnerability. Stop everything until you fix that!
btnfind_Click doesn't need to end up calling cust.Search() twice.
private void btnfind_Click(object sender, EventArgs e)
{
//<snip>
// no need to do all this twice.
// DataTable dt = new DataTable();
// dt = cust.Search();
// dgCustomer.DataSource = dt;
RefreshGrid();
}
Your RefreshGrid method is overwriting the DataSource you set in btnfind_Click... don't call it, just call DataBind
private void btnfind_Click(object sender, EventArgs e)
{
...
DataTable dt = cust.Search();
dgCustomer.DataSource = dt;
dgCustomer.DataBind();
}
By the way, you don't need to assign a new DataTable to dt if you're immediately setting it to the result of cust.Search... you're just creating an instance for nothing (I fixed it in the code above)