sorting DGV on header click - c#

Currently my system is connected via mysql data base to get the data from mysql to dgv.
I need a code that can blend with my current code on sorting the data when clicked on header. Sorry for poor english.
private void btnDisplay_Click(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString; //Set your MySQL connection string here.
string query = "SELECT lrn,first_name,middle_name,last_name,grade_and_section,student_gender,student_guardian,contact_number FROM student_info;"; // set query to fetch data "Select * from tabelname";
using (MySqlConnection conn = new MySqlConnection(connString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dataStudent.DataSource = ds.Tables[0];
dataStudent.Columns[0].HeaderCell.Value = "LRN";
dataStudent.Columns[1].HeaderCell.Value = "First Name";
dataStudent.Columns[2].HeaderCell.Value = "Middle Name";
dataStudent.Columns[3].HeaderCell.Value = "Last Name";
dataStudent.Columns[4].HeaderCell.Value = "Grade And Section";
dataStudent.Columns[5].HeaderCell.Value = "Gender";
dataStudent.Columns[6].HeaderCell.Value = "Guardian";
dataStudent.Columns[7].HeaderCell.Value = "Contact Number";
dataStudent.Columns[5].Visible = false;
dataStudent.Columns[6].Visible = false;
dataStudent.Columns[7].Visible = false;
}
}
}
private void dataStudent_CellClick(object sender, DataGridViewCellEventArgs e)
{
int index = e.RowIndex;
DataGridViewRow selectedRow = dataStudent.Rows[index];
txtLRN.Text = selectedRow.Cells[0].Value.ToString();
txtFName.Text = selectedRow.Cells[1].Value.ToString();
txtMName.Text = selectedRow.Cells[2].Value.ToString();
txtLName.Text = selectedRow.Cells[3].Value.ToString();
txtYear.Text = selectedRow.Cells[4].Value.ToString();
txtGender.Text = selectedRow.Cells[5].Value.ToString();
txtGuardian.Text = selectedRow.Cells[6].Value.ToString();
txtContact.Text = selectedRow.Cells[7].Value.ToString();
}

Related

Set value of combo box to collected value from source

I have a form with two combo boxes which both have a list from a database. In this case one is a list of countries and based on the value selected there, the second list is updated to show only the cities that belong to the selected country. After that, the values are combined and stored in my program like "city, country".
When I open my form I retrieve that information and separate the values back to just country and city. All working. The trouble I have now is that the comboboxes should display the retrieved values if the correspond to a value found in the list/database. I tried as shown below, but that is not working. I guess it has something to do with adding a new row to the database to show "--Select Country--" and "--Select City--".
I hope you can point me in the right direction. Thank you all in advance for your replies.
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
public partial class FormPropertyEditor : Form
{
//Connect to local database.mdf
SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
#"C:\Users\gleonvanlier\AppData\Roaming\Autodesk\ApplicationPlugins\MHS Property Editor\Database.mdf;" +
"Integrated Security=True;Connect Timeout=30;User Instance=False;");
DataRow dr;
public FormPropertyEditor()
{
InitializeComponent();
ReadProperties();
refreshdata();
}
public void refreshdata()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCountries Order by CountryName", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, "--Select Country--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCountry.ValueMember = "CountryID";
comboBoxCountry.DisplayMember = "CountryName";
comboBoxCountry.DataSource = dt;
comboBoxCountry.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCountry.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void comboBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxCountry.SelectedValue.ToString() != null)
{
int CountryID = Convert.ToInt32(comboBoxCountry.SelectedValue.ToString());
refreshstate(CountryID);
}
}
public void refreshstate(int CountryID)
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCities where CountryID= #CountryID Order by CityName", con);
cmd.Parameters.AddWithValue("CountryID", CountryID);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, 0, "--Select City--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCity.ValueMember = "CityID";
comboBoxCity.DisplayMember = "CityName";
comboBoxCity.DataSource = dt;
comboBoxCity.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCity.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void ReadProperties()
{
string progId = "Inventor.Application";
Type inventorApplicationType = Type.GetTypeFromProgID(progId);
Inventor.Application invApp = (Inventor.Application)Marshal.GetActiveObject(progId);
//Get the active document in Inventor
Document oDoc = (Document)invApp.ActiveDocument;
ReadProperties readProperties = new ReadProperties();
//Read Customer
string txtCustomer = readProperties.ReadCustomProperty("Customer", oDoc).ToString();
this.textBoxCustomer.Text = txtCustomer;
//Read Location
string txtLocation = readProperties.ReadCustomProperty("Location", oDoc).ToString();
try
{
string[] location = txtLocation.Split(',', ' ');
string city = location[0];
string country = location[1];
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
}
catch (Exception e)
{
string city = string.Empty;
string country = string.Empty;
}
}
This solved it:
comboBoxCountry.SelectedIndex = comboBoxCountry.FindStringExact(country);
comboBoxCity.SelectedIndex = comboBoxCity.FindStringExact(city);

GridView_RowUpdating method doesn't works in my asp.net project

I have an asp.net project, in which columns in GridView adding manually by button click, here's the method:
protected void addVacations_Click(object sender, EventArgs e)
{
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("insert into vacations(id,name,date,nodes) values(DEFAULT, #imya, #data, #primVac)", conn);
cmd.Parameters.Add(new NpgsqlParameter("#imya", imya.Text));
cmd.Parameters.Add(new NpgsqlParameter("#data", data.Text));
cmd.Parameters.Add(new NpgsqlParameter("#primVac", primVac.Text));
cmd.ExecuteNonQuery();
Response.Redirect(Request.RawUrl);
}
}
I have two others buttons, that adding change GridView's columns by clicking them.
Now i have to add opportunity to change them online by clients. Here's the GridView code:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1650px" AutoGenerateDeleteButton="True" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowEditing="GridView1_RowEditing" AutoGenerateEditButton="True" >
Here's GridView1_RowUpdating method:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int ID5 = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string name = (row.FindControl("name") as TextBox).Text;
string date = (row.FindControl("date") as TextBox).Text;
string prim = (row.FindControl("nodes") as TextBox).Text;
string constr = ConfigurationManager.ConnectionStrings["postgresConnectionString"].ConnectionString;
using (NpgsqlConnection cn = new NpgsqlConnection(constr))
{
string query = "UPDATE vacations SET name=#name,date=#date,nodes=#prim Where id=#ID5";
NpgsqlCommand cmd = new NpgsqlCommand(query, cn);
cmd.Parameters.Add("#name", NpgsqlDbType.Varchar).Value = name;
cmd.Parameters.Add("#date", NpgsqlDbType.Varchar).Value = date;
cmd.Parameters.Add("#nodes", NpgsqlDbType.Varchar).Value = prim;
cmd.Parameters.Add("#id", NpgsqlDbType.Integer).Value = ID5;
cn.Open();
cmd.ExecuteNonQuery();
}
}
Right now i have next error when trying to change rows:
Server error in the application '/'.
The object reference does not point to an instance of the object.
Description: An unhandled exception occurred during the execution of the current web request. Examine the stack trace for more information about this error and the code snippet that caused it.
Exception Information: System.NullReferenceException: The object reference does not point to an instance of the object.
Source error:
Line 361: GridViewRow row = GridView1.Rows[e.RowIndex];
Line 362: int ID5 = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
Line 363: string name = (row.FindControl("name") as TextBox).Text;
The problem exactly in Line 363
I think the problem in my string, if be exact here:
string name = (row.FindControl("name") as TextBox).Text;
string date = (row.FindControl("date") as TextBox).Text;
string prim = (row.FindControl("nodes") as TextBox).Text;
So i need help how to correctly declare my strings? Or what wrong in my code.
Update. Here is my column details, all three buttons:
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = null;//надо удалить текущие колонны (columns)
GridView1.DataBind();
for (int i = 0; GridView1.Columns.Count > i;)
{
GridView1.Columns.RemoveAt(i);
}
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
bf1.HeaderText = "Направление деятельности";
bf1.DataField = "lineofbusiness";
bf1.ReadOnly = true;
bf1.SortExpression = "Napr";
bf2.HeaderText = "Объект";
bf2.DataField = "object";
bf2.SortExpression = "Obj";
bf3.HeaderText = "Мероприятия";
bf3.DataField = "events";
bf3.SortExpression = "Merop";
bf4.HeaderText = "Срок";
bf4.DataField = "deadline";
bf4.SortExpression = "Srok";
bf5.HeaderText = "Примечания";
bf5.DataField = "nodes";
bf5.SortExpression = "Prim";
GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(bf4);
GridView1.Columns.Add(bf5);
NpgsqlCommand cmd = new NpgsqlCommand();
NpgsqlDataAdapter sqlDa = new NpgsqlDataAdapter("SELECT id, lineofbusiness, object, events, deadline, nodes FROM mainpage where executor = '" + (string)Session["Name"] + "' ", conn);
//NpgsqlDataAdapter sqlDa1 = new NpgsqlDataAdapter("SELECT lineofbusiness, object, events, deadline, nodes FROM mainpage where executor = '" + curentExec + "' ", conn); //показ по исполнителю(раб код)
DataTable dtbl = new DataTable();
sqlDa.Fill(dtbl);
GridView1.DataSource = dtbl;
GridView1.DataBind();
Panel2.Visible = false;
Panel1.Visible = true;
Panel3.Visible = false;
//conn.Close(); //надо ли?
}
}
protected void Button2_Click(object sender, EventArgs e)
{
GridView1.DataSource = null;//надо удалить текущие колонны (columns)
GridView1.DataBind();
for (int i = 0; GridView1.Columns.Count > i;)
{
GridView1.Columns.RemoveAt(i);
}
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
bf1.HeaderText = "Номер";
bf1.DataField = "id";
bf1.ReadOnly = true;
bf1.SortExpression = "11";
//bf2.HeaderText = "ФИО";
//bf2.DataField = "name";
//bf2.SortExpression = "22";
bf3.HeaderText = "Место";
bf3.DataField = "place";
bf3.SortExpression = "33";
bf4.HeaderText = "Цель";
bf4.DataField = "target";
bf4.SortExpression = "44";
bf5.HeaderText = "Срок";
bf5.DataField = "date";
bf5.SortExpression = "44";
bf6.HeaderText = "Результат";
bf6.DataField = "result";
bf6.SortExpression = "44";
GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(bf4);
GridView1.Columns.Add(bf5);
GridView1.Columns.Add(bf6);
NpgsqlCommand cmd = new NpgsqlCommand();
//NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT * FROM trips", conn);
NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT id, place, target, date, result FROM trips where name = '" + (string)Session["Name"] + "' ", conn);
DataTable dtblvac = new DataTable();
sqlDavac.Fill(dtblvac);
GridView1.DataSource = dtblvac;
GridView1.DataBind();
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = true;
}
}
protected void Button3_Click(object sender, EventArgs e)
{
GridView1.DataSource = null;//надо удалить текущие колонны (columns)
GridView1.DataBind();
for (int i = 0; GridView1.Columns.Count > i;)
{
GridView1.Columns.RemoveAt(i);
}
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
bf1.HeaderText = "Номер";
bf1.DataField = "id";
bf1.ReadOnly = true;
bf1.SortExpression = "NomerVac";
//bf2.HeaderText = "ФИО";
//bf2.DataField = "name";
//bf2.SortExpression = "NameVac";
bf3.HeaderText = "Дата";
bf3.DataField = "date";
bf3.SortExpression = "DataVac";
bf4.HeaderText = "Примечания";
bf4.DataField = "nodes";
bf4.SortExpression = "PrimVac";
GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(bf4);
NpgsqlCommand cmd = new NpgsqlCommand();
//NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT * FROM vacations", conn);
NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT id, date, nodes FROM vacations where name = '" + (string)Session["Name"] + "' ", conn);
DataTable dtblvac = new DataTable();
sqlDavac.Fill(dtblvac);
GridView1.DataSource = dtblvac;
GridView1.DataBind();
Panel1.Visible = false;
Panel2.Visible = true;
Panel3.Visible = false;
}
}

Creating column Combobox in Datagridview

I am new to C#. I want to create combobox in first column of my Datagridview. Following is the routine I have wrote. But it is adding combo in last column after setting up my grid.
For setting up Grid, i have tried the below code:
private void SetGrid()
{
dgDetail.AutoGenerateColumns = false;
dgDetail.ColumnCount = 5;
dgDetail.Columns[0].Name = "Debit";
dgDetail.Columns[0].HeaderText = "Debit Account Name";
dgDetail.Columns[1].Name = "Bank";
dgDetail.Columns[1].HeaderText = "Bank";
dgDetail.Columns[2].Name = "ChqNo";
dgDetail.Columns[2].HeaderText = "CC/Chq No";
dgDetail.Columns[3].Name = "ChqDate";
dgDetail.Columns[3].HeaderText = "Chq Date";
dgDetail.Columns[4].Name = "Amount";
dgDetail.Columns[4].HeaderText = "Amount";
dgDetail.AllowUserToDeleteRows = true;
dgDetail.Columns[0].Width = 280;
dgDetail.Columns[1].Width = 160;
dgDetail.Columns[2].Width = 90;
dgDetail.Columns[3].Width = 90;
dgDetail.Columns[4].Width = 120;
dgDetail.RowsDefaultCellStyle.ForeColor = Color.Black;
dgDetail.RowsDefaultCellStyle.BackColor = Color.White;
dgDetail.Font = new Font("Arial", 9, FontStyle.Regular);
}
For Creating the combobox which is filled from DB.
private void FillGridCombo()
{
SqlConnection sqlConnection = new SqlConnection(strCon);
sqlConnection.Open();
try
{
string selectQueryStringMonth = "SELECT accode, GLAC FROM glmast where (actype = 'CSH' and titleac <> 'PDP') OR TITLEAC = 'DIS' ORDER BY GLAC";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectQueryStringMonth, sqlConnection);
SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
BindingSource bindingSourceMonth = new BindingSource();
bindingSource.DataSource = dataTable;
//Adding Combo
DataGridViewComboBoxColumn ColumnAcc = new DataGridViewComboBoxColumn();
ColumnAcc.DataPropertyName = "Debit Account Name";
ColumnAcc.HeaderText = "Debit Account Name";
ColumnAcc.Width = 280;
ColumnAcc.DataSource = bindingSourceMonth;
ColumnAcc.ValueMember = "accode";
ColumnAcc.DisplayMember = "GLAC";
dgDetail.Columns.Add(ColumnAcc);
dgDetail.DataSource = bindingSource;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (sqlConnection.State != ConnectionState.Closed)
sqlConnection.Close();
}
}
I am calling both procedures on my NewData() like this.
private void NewData()
{
if (dgDetail.DataSource != null)
dgDetail.DataSource = null;
else
dgDetail.Rows.Clear();
ClearData();
CtrlEnable();
SetGrid();
FillGridCombo();
}
Help / Guide me to achieve this.,
use
dgDetail.Columns.Insert(0, ColumnAcc);
instead of
dgDetail.Columns.Add(ColumnAcc);
when you use Add it simply adds it as the last column, while using Insert you can choose where to add it to.
public virtual void Insert( int columnIndex, DataGridViewColumn
dataGridViewColumn )
note that the columnIndex is a zero-based index so 0 is the first column
You can use the Insert method instead of Add like this:
dgDetail.Columns.Insert(0,ColumnAcc);

Apply Column Filtering in Gridview in asp.net

I have a gridview which is populated at runtime with a table with unknow number of columns which are not known before hand.
I want to apply column filtering on all columns with Drop Down List.
How can I achieve it. Using Jquery, Linq or simple C sharp Coding.
public partial class DetailView : System.Web.UI.Page
{
public static int y = 0;
public static String colName = "";
public static Boolean flag = false;
static String folder = "";
static public MySqlConnection conn = null;
static public DropDownList dp = null;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string strcon = ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
conn = new MySqlConnection(strcon);
conn.Open();
Response.Write(Session["cols"].ToString());
Response.Write(Session["id"].ToString());
// Response.Write("qw");
folder = Session["folderName"].ToString();
colName = Session["cols"].ToString();
GridBind(folder, colName, flag);
}
protected void Page_Load(object sender, EventArgs e)
{
}
public void GridBind(String folder, String colName, Boolean val)
{
GridView1.DataSource = null;
GridView1.DataBind();
GridView1.Columns.Clear();
y = 0;
MySqlDataAdapter da;
if (val == false)
{
da = new MySqlDataAdapter("select * from " + folder + "", conn);
}
else
{
da = new MySqlDataAdapter("select * from " + folder + " where abc= '" + colName + "'", conn);
}
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataColumn coloumn in dt.Columns)
{
if (!coloumn.ColumnName.Equals("emp"))
{
var linkF = new TemplateField();
linkF.HeaderText = coloumn.ColumnName;
linkF.HeaderTemplate = new LinkColumn(ListItemType.Header, coloumn.ColumnName,folder);
linkF.ItemTemplate = new LinkColumn(ListItemType.Item, coloumn.ColumnName,folder);
GridView1.Columns.Add(linkF);
}
else if (coloumn.ColumnName.Equals("emp"))
{
//Response.Write("Came");
BoundField bfield = new BoundField();
////Initalize the DataField value.
bfield.DataField = coloumn.ColumnName;
////Initialize the HeaderText field value.
bfield.HeaderText = coloumn.ColumnName;
GridView1.Columns.Add(bfield);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
class LinkColumn : DetailView, ITemplate
{
int id;
ListItemType _item;
String colN = null;
String fold;
public LinkColumn(ListItemType item, String colNa, String f)
{
_item = item;
colN = colNa;
fold = f;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_item)
{
case ListItemType.Header:
DetailView.dp = new DropDownList();
Label lb = new Label();
MySqlCommand cm = new MySqlCommand("select distinct " + colN + " from " + fold + "", conn);
MySqlDataAdapter ad = new MySqlDataAdapter();
DataTable d = new DataTable();
ad.SelectCommand = cm;
ad.Fill(d);
DetailView.dp.DataTextField = colN;
DetailView.dp.DataValueField = colN;
DetailView.dp.DataSource = d;
DetailView.dp.DataBind();
lb.Text = colN.ToUpperInvariant();
dp.AutoPostBack = true;
dp.EnableViewState = true;
// DetailView.dp.ID = y.ToString();
y++;
container.Controls.Add(lb);
container.Controls.Add(DetailView.dp);
// DetailView.dp.ID = DetailView.y.ToString();
// Response.Write(_Default.dp.ID);
DetailView.dp.SelectedIndexChanged += new EventHandler(dp_Selected);
break;
case ListItemType.Item:
TextBox tb1 = new TextBox();
tb1.Enabled = false;
tb1.DataBinding += new EventHandler(tb1_Data);
tb1.Columns = 30;
container.Controls.Add(tb1);
break;
}
}
void tb1_Data(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow cont = (GridViewRow)txt.NamingContainer;
object dataV = DataBinder.Eval(cont.DataItem, colN);
if (dataV != DBNull.Value)
{
txt.Text = dataV.ToString();
}
}
void dp_Selected(object sender, EventArgs e)
{
DataTable a = new DataTable();
DropDownList list = (DropDownList)sender;
String name = list.SelectedValue;
// String ID = list.ID.ToString();
// Session["id"] = ID;
Session["cols"] = name;
DetailView.colName = Session["cols"].ToString();
DetailView.flag = true;
// Response.Write(DetailView.colName);
GridBind(fold, DetailView.colName, true);
}
}
}
When i am calling GridBind function from event handler it is giving Null pointer Excpetion at GridView1.DataSource = null;
My GridView1 is present in DetailView.aspx
}
Any help be highly appreciated
Thanks

Data in data grid view won't show visually C# SQL

I have this data grid view like this:
But it should be like this:
The data is successfully fetched but I have to drag the cells so the data can be shown.
This is the code:
private void button5_Click_1(object sender, EventArgs e)
{
sqlConnStaff();
groupBoxRoom.Visible = false;
groupBoxDPenghuni.Visible = false;
groupBoxPenghasilan.Visible = false;
groupBoxPenghuni.Visible = false;
groupBoxStaff.Visible = true;
GroupBox_AddResident_Resident.Visible = false;
GroupBox_AddResident_Room.Visible = false;
GroupBox_AddResident1.Visible = false;
GroupBox_DeleteResident_Resident.Visible = false;
GroupBox_DeleteResident1.Visible = false;
GroupBox_Resident.Visible = false;
GroupBox_Update_Room.Visible = false;
GroupBox_UpdateResident1.Visible = false;
}
private void sqlConnStaff()
{
BindingSource dbBindSource = new BindingSource();
SqlCommand com;
com = new SqlCommand();
SqlConnection con = new SqlConnection(strCon);
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "view_staff";
SqlDataAdapter dataAdapter = new SqlDataAdapter(com);
IDCabang = new SqlParameter();
IDCabang.SqlDbType = SqlDbType.VarChar;
IDCabang.Size = 5;
IDCabang.ParameterName = "#IDCabang";
IDCabang.Value = IDCabangC;
IDCabang.Direction = ParameterDirection.Input;
com.Parameters.Add(IDCabang);
con.Open();
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
dbBindSource.DataSource = table;
dataGridView3.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
// you can make it grid readonly.
dataGridView3.ReadOnly = true;
// finally bind the data to the grid
dataGridView3.DataSource = dbBindSource;
con.Close();
}
Whats wrong and what should I do?
It looks like problem is not with your c# code but the coloring scheme. When you select cells the data is visible, which means you must change fore color to something other than white.

Categories

Resources