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.
Related
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);
I want to display a Comboxbox Item, depending on a data table.
for example:
1 = open
2 = close
....
The combobox content is created with the datatable:
string sqlStr = "select id, description from sdg.pa_status";
MySqlDataAdapter adapt = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand();
DataSet ds = new DataSet();
cmd = new MySqlCommand(sqlStr, conn);
adapt.SelectCommand = cmd;
adapt.Fill(ds);
**_status** = ds.Tables[0];
combox is created:
column.Name = "status";
column.DropDownWidth = 160;
column.Width = 160;
column.FlatStyle = 0;
column.HeaderText = "Status";
column.DataSource = **_status**;
column.DataPropertyName = dGVQuote.Columns["**stat**"].ToString();
column.ValueMember = _status.Columns[1].ToString();
column.DisplayMember = _status.Columns[1].ToString();
datagrid is generated:
private void CustomizeDataGridViewOrder()
{
dGVQuote.DataSource = GetQuote("");
dGVQuote.Columns["ID"].Width = 135;
dGVQuote.Columns["ID"].HeaderText = "Angebotsnummer";
dGVQuote.Columns["idorder"].Visible = false;
dGVQuote.Columns["Description"].Width = 225;
dGVQuote.Columns["Description"].HeaderText = "Beschreibung";
dGVQuote.Columns["comment"].Width = 225;
dGVQuote.Columns["comment"].HeaderText = "interner Kommentar";
dGVQuote.Columns["idcust"].Visible = false;
dGVQuote.Columns["idobj"].Visible = false;
dGVQuote.Columns["cnt"].Width = 60;
dGVQuote.Columns["cnt"].HeaderText = "Anzahl MA";
dGVQuote.Columns["**stat**"].Visible = true;
dGVQuote.Columns.Add(CreateComboBoxColumn());
dGVQuote.Columns["valid"].Width = 135;
dGVQuote.Columns["valid"].HeaderText = "gültig bis";
dGVQuote.DataSource = GetQuote(""); //datatable is handed over
I am desperate. Can someone help me?
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;
}
}
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 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);