In my grid view i wants to insert new records to the last row of grid view. so i set Gridview2.Allowsorting is false. but it doesn't works on my grid view. my code is here
public void gridview2_selectgroup()
{
if (Session["selectedgroupes"] != null)
{
ArrayList groups = new ArrayList();
ArrayList student_id_list = new ArrayList();
groups = (ArrayList)Session["selectedgroupes"];
student_id_list=(ArrayList)Session["STUDENT_ID"];
string select_string="SELECT student_name,student_id,student_nric,student_group FROM student_details WHERE student_group='"+groups[0].ToString().Trim()+"' ";
for(int i=1;i<groups.Count;i++)
{
select_string+= " or student_group='"+groups[i].ToString().Trim()+"'";
}
if(Session["STUDENT_ID"]!=null)
{
for(int i=0;i<student_id_list.Count;i++)
{
select_string+= " or student_id='"+student_id_list[i].ToString().Trim()+"'";
}
}
SqlConnection con = obj.getcon();
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(select_string, con);
adapter.Fill(ds);
GridView2.DataSource = ds;
GridView2.AllowSorting = false;
GridView2.DataBind();
con.Close();
}
what will be the reason? It works on another grid views on my project . please help
Click on your gridview in .aspx page and hit f4. The properties window will popup. There u check the 5th line (Allow Sorting).If its true make it false. Sometimes the codebehind code will not work due to timings.If its already false then place your "GridView2.AllowSorting = false;" in between datasource and databind.
GridView2.DataSource = ds;
GridView2.AllowSorting = false;
GridView2.DataBind();
try this
string select_string="SELECT student_id,student_name,student_nric,student_group FROM student_details WHERE student_group='"+groups[0].ToString().Trim()+"' ";
Related
I am building a web form. I have one search field and a search button. I am connecting to MS Access database to retrieve and display the result on the grid view. But my grid view is not appearing on the web page.
Can anyone please help me to find out where I am wrong?
Here is my aspx.cs code:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Smita\\Desktop\\Project.accdb");
DataTable dt = new DataTable() ;
if (txtMerchant.Text.Length > 0)
{
con.Open();
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand("select * from Test where Merchant ID like '" + txtMerchant.Text + "%'", con);
DBAdapter.Fill(dt);
GridView1.DataSource = dt;
}
You have to call the DataBind, binding method first after you assign the data source.
Like that:
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.DataSource = dt; //Assigned a blank table.
"dt" Doesn't seem to point to anything.
I'm still learning C# and winform and I can't seem to find a fix to my problem. The problem is whenever I select items in my sql generated checkedlistbox and press the button2 event it won't show the actual data, it just shows "System.Data.DataRowView" am I missing something here is the code..
private void button2_Click(object sender, EventArgs e)
{
int counter = checkedListBox1.SelectedItems.Count;
List<string> selecteditems = new List<string>();
for (int i = 0; i < counter; i++)
{
selecteditems.Add(checkedListBox1.SelectedItems[i].ToString());
}
MessageBox.Show(selecteditems[0]);
for the generation of checkedlistbox here is the code.
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tbl_members ORDER BY Position", con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("FullName", typeof(string));
dt.Load(reader);
DataSet ds = new DataSet();
adapter.Fill(ds);
checkedListBox1.DataSource = ds.Tables[0];
checkedListBox1.DisplayMember = "FullName";
checkedListBox1.ValueMember = "FullName";
checkedListBox1.Enabled = true;
checkedListBox1.Refresh();
count = Convert.ToInt32(numericUpDown1.Value);
con.Close();
Try replace your for loop in button2_Click to this:
foreach (DataRowView rowView in checkedListBox1.CheckedItems)
{
selecteditems.Add(rowView["FullName"].ToString());
}
there is both
MessageBox.Show(checkedListBox1.CheckedItems[0].ToString());
and
MessageBox.Show(checkedListBox1.SelectedItems[0].ToString());
use them according to your need I think you were looking for first one
Try using Convert.ToString(checkedListBox1.SelectedItems[i]) instead of .ToString()
.ToString() generally returns variable's class name in string if `.ToString()' not overrided by class.
I have a DataGridView made of a DataSet of a table from the DB. When I delete a row, it is updated in the database but it is not removed from the GridView. Only when I restart the application does it get removed from the GridView.
Please help
You need to reset the binding on your bindingsource.
bindingSource.ResetBindings(false);
This is a very simple process.
1.) Create a Binding Source
2.) Set the Datasource for this object to your Dataset Table.
3.) Set The datasource for your DatagridView as the Binding source Object.
Code Example:
Dataset ds = new Dataset();
BindingSource bs = new BindingSource()
bs.Datasource = ds.Table[0];
DatagridView.Datasource = bs;
Now, Any changes you make in the DataTable will ripple through to your GridView automatically.
Hope this helps you?
if you are showing your table in dgv and for deleting something from that table you have a button on your win form. you chose let's say ID and click "delete" button for delting an item from db table. Here is that code:
private void btn_Delete_Click(object sender, EventArgs e)
{
int selectedCellCount = dgv.GetCellCount(DataGridViewElementStates.Selected);
if (selectedCellCount > 0)
{
string selection;
for (int i = 0; i < selectedCellCount; i++)
{
selection = dgv.SelectedCells[i].Value.ToString();
string qs_delete = "DELETE FROM yor_table WHERE id = '" + selection + "';";
try
{
conn = new MySqlConnection(cs);
conn.Open();
cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = qs_delete;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
}
//don't forget to load your table again in dgv
string qs_select = "SELECT * FROM your_table";
System.Data.DataTable dataTable = new System.Data.DataTable();
dataTable.Clear();
dgv.DataSource = dataTable;
try
{
conn = new MySqlConnection(cs);
cmd = new MySqlCommand(qs_select, conn);
conn.Open();
da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
cb = new MySqlCommandBuilder(da);
dgv.DataSource = dataTable;
dgv.DataMember = dataTable.TableName;
dgv.AutoResizeColumns();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
You'll notice here that i have MySQL db but don't bother yourself with that.
If database is updated and you want to refresh DataGridView, call this:
this.<table name>TableAdapter.Fill(this.<DB name>DataSet.<table name>);
For example: Where is name of your table (for example Customers) and is name of your database (for example MyDB).
this.CustomersTableAdapter.Fill(this.MyDBDataSet.Customers);
You have to call this function after every deletion(Re-bind Grid).
void BindGrid()
{
YourDataGridView.DataSource = dataset;
YourDataGridView.DataBind();
}
I have written the following code to display the fields of my choice in DataGrid. What I want to do is to hide the ID column of COUNTRY table in the DataGrid. So it should not appear to the user. But I also want to still get the ID of COUNTRY table record if the user click on any column or sorts the DataGrid.
Kindly help me. What should I do? What is missing in this code?
OleDbDataAdapter da;
DataSet ds;
public void showGrid()
{
OleDbConnection conn = new OleDbConnection(ConnString);
string sql = #"Select id, country_code, country_name , from country";
OleDbDataAdapter da = new OleDbDataAdapter(sql,conn);
try
{
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "Cat");
// Turn this off so column names do not come from data source
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Cat";
dataGridView1.Columns[0].HeaderText = "Code";
dataGridView1.Columns[1].HeaderText = "Name";
dataGridView1.Columns[0].Name = "country_code";
dataGridView1.Columns[1].Name = "country_name";
dataGridView1.Columns[0].DataPropertyName = "country_code" ;
dataGridView1.Columns[1].DataPropertyName = "country_name";
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
Add this line in Form1_Load method
dataGridView1.Columns[0].Visible = false;
Please Mark as Answer, if this solves your problem
i m using c# as front end and ms access as back end
I m displaying the datagrid only when the index in the combo box is changed
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
refershGridView(comboBox1.Text);
}
but when I make any updates to the data grid ,the update reflects only after i make a selected index change event
i tried datagidview1.refresh() and also called my refershGridView(comboBox1.Text) functions implicitly
but my grid view refreshes only when i make a selected index change
code for refershGridView(comboBox1.Text)
private void refershGridView(string tableName)
{
saveBttnSwitch = 0;//for save button swicth
//setting back to intial user interface ..
clearVisibilty();
clearall();
button1.Visible = true;
button3.Visible = false;
label11.Visible = false;
try
{
OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString = ConnString;
//create the database query
string query = null;
if (tableName == "employee")
{
query = "SELECT fname,lname,ssn FROM employee";
dataGridView1.Visible = true;
}
if (tableName == "project")
{
query = "SELECT pname,pnumber FROM project";
dataGridView1.Visible = true;
}
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, mycon);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
try
{
dAdapter.Fill(dTable);
}
catch (OleDbException exp)
{
label11.Text = "file couldnt be found...kindly check Db file location ";
label11.Visible = true;
button1.Visible = false;
}
// DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridView1.DataSource = bSource;
// dataGridView1.Dock = DockStyle.Fill;
dataGridView1.AutoGenerateColumns = true;
mycon.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new InvalidOperationException("Data could not be read", ex);
}
this.button2.Visible = false;
}
Does refershGridView(comboBox1.Text); refill the DataGrid?
If so, call it from any other place where you want your data to be refilled. If SelectedIndexChanged even of the combo is the only place you are filling it, it won't refresh unless you change a selection.
And as #Bryan suggests, its better if we see some code.
Try to clear the dTable and dataGridView1.DataSource before you fill the DataTable and sets the DataGridView DataSource
dTable = new DataTable();
dataGridView1.DataSource = nothing;