I want to change a specific text in my gridview here's an image below:
Example if I click the checkbox button the specific row "Status" text is change to "Validated".
This is my aspx code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using MSSQLConnector;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class TeacherPage : System.Web.UI.Page
{
private MSConnector connector = new MSConnector();
private DataSet SubjectlistData;
private DataTable SubjectlistTable;
string query = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Populate The Select Tag with Subjects
SubjectList.DataSource = Session["TeacherSubjectList"];
SubjectList.DataTextField = "CourseNo";
SubjectList.DataValueField = "CourseNo";
SubjectList.DataBind();
}
}
}
protected void TeacherSubjects_Click(object sender, EventArgs e)
{
string getText = SubjectList.SelectedItem.Text;
//Connection String
connector.ConnectionString = "Data Source=keith;Initial Catalog=SAD;Integrated Security=True";
query = "select StudentID,CourseNo,CourseDescription,Units,Day,StartTime,EndTime,Room,Instructor,Amount,Status from assessmentform where CourseNo = '" + getText + "'";
SubjectlistData = connector.ExecuteQuery(query);
SubjectlistTable = SubjectlistData.Tables[0];
//Add a colum check row
SubjectlistTable.Columns.Add("Check", Type.GetType("System.Boolean"));
Session["ValidateSubject"] = SubjectlistTable;
Response.Redirect("ValidateSubjectTeacher.aspx");
}
I add a checkbox in my row to my gridview using this:
//Add a colum check row
SubjectlistTable.Columns.Add("Check", Type.GetType("System.Boolean"));
Session["ValidateSubject"] = SubjectlistTable;
I pass my gridview using session to another page,
its aspx code behind ValidatePage:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class ValidateSubjectTeacher : System.Web.UI.Page
{
CheckBox check = new CheckBox();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ValidateSubject"] == null)
{
Response.Redirect("TeacherPage.aspx", true);
}
if (!IsPostBack)
{
ValidateSubject.DataSource = Session["ValidateSubject"];
ValidateSubject.DataBind();
}
//I add my checkbox in the last row using this
foreach (GridViewRow row in ValidateSubject.Rows)
{
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox;
check.Enabled = true;
}
}
protected void ValidateSubject_Click(object sender, EventArgs e)
{
if(check.Checked)
{
//This condition here is I want to change the Status when check to validated.
}
}
}
in my code behind using session I bind all the data in DataTable(FirstPage);
DataSet ds = connector.ExecuteQuery(query);
DataTable dt = dt.Table[0];
dt.DataBind();
Session["SubjectList"] = dt;
You can use the NamingContainer property like this:-
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk= (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give you row
grvRow.Cells[10].Text = "Validated"; //Updated the cell text in that row.
//Or if Status is a control like label then //
Label StatusLabel = (Label)grvRow.FindControl("StatusLabel");
StatusLabel.Text = "Validated";
}
Alternatively, you can also use the RowDataBound event.
Update:
Since you are binding the grid with directly i.e. AutoGenerateColumns set as true, you will have to attach the event handler of checkbox programmatically as well like this:-
//I add my checkbox in the last row using this
foreach (GridViewRow row in ValidateSubject.Rows)
{
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox;
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event
check.AutoPostBack = true; //Set the AutoPostBack property to true
}
Now, in your event first find the row with the help of checkbox, then update the Status column like this:-
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk= (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give you row
if(chk.Checked)
{
grvRow.Cells[10].Text = "Validated";
}
}
You can use an Extension Method like this:
public static class myExtensionsMethods
{
public static void validateRow(this object sender)
{
int columnIndex = 10;
GridViewRow myRow = ((Control)sender).Parent as GridViewRow;
myRow.Cells[columnIndex].Text = "Validated";
}
}
The extension method will allow you to call it in this way
protected void ValidateSubject_Click(object sender, EventArgs e)
{
if (check.Checked)
{
sender.validateRow();
}
}
Related
I am trying to get the cell value in a string from the selected cell in the "Document Number" column in a DataGridView. My code to retrieve data from SharePoint and populate the DataGridView works fine, but I seem to be caught in a loop there? I cannot execute any other methods after populating the DataGridView . I can select a new search term and execute the Button1_Click event again successfully, but I cannot get any other methods to execute?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace BuyersForeverFriend
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string userSearch = textBox1.Text;
button1.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
using (ClientContext ctx = new ClientContext("https://teamsites.nafta.fcagroup.com/sites/PSOAPPS/iws/"))
{
var userInput = textBox1.Text;
Web web = ctx.Web;
List list = web.Lists.GetById(new Guid("61ef6657-eff7-42cb-99e1-8afd590334ec"));
var q = new CamlQuery() { ViewXml = "<View><Query><Where><Contains><FieldRef Name='Item_x0020_Description' /><Value Type='Note'>" + userInput + "</Value></Contains></Where></Query><ViewFields><FieldRef Name='Title' /><FieldRef Name='Topic_x002d_' /><FieldRef Name='Item_x0020_Description' /></ViewFields><QueryOptions /></View>" };
var r = list.GetItems(q);
ctx.Load(r);
ctx.ExecuteQuery();
if (r.Count != 0)
{
var searchResults = new DataTable();
searchResults.Columns.AddRange(new[]
{
new DataColumn("ID"), new DataColumn("Document Number"), new DataColumn("Item Description"), new DataColumn("Topic")});
foreach (var oListItem in r)
{
searchResults.Rows.Add(oListItem["ID"], oListItem["Title"], oListItem["Item_x0020_Description"],
oListItem["Topic_x002d_"]);
}
if (dataGridView1 != null)
{
dataGridView1.DataSource = searchResults;
dataGridView1.Refresh();
dataGridView1.Columns[2].DefaultCellStyle.Format = "dd'/'MM'/'yyyy";
var dataGridViewColumn = dataGridView1.Columns["ID"];
if (dataGridViewColumn != null)
dataGridViewColumn.Visible = false;
}
else
MessageBox.Show("after else statement");
}
}
MessageBox.Show("after sharepoint if statement");
return;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("a cell was clicked");
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
MessageBox.Show("starting routine");
if (dataGridView1.SelectedCells.Count > 0)
{
int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
string a = Convert.ToString(selectedRow.Cells["Document Number"].Value);
MessageBox.Show(a);
textBox2.Text = ("The var =" + a);
}
else MessageBox.Show("if did not end up true");
}
}
}
I failed to initialize these, after adding them to the form method...poof everything works! :
public Form1()
{
InitializeComponent();
dataGridView1.CellClick += dataGridView1_CellClick;
dataGridView1.SelectionChanged += dataGridView1_SelectionChanged;
}
I am having some trouble with this code, I am passing rows from one Grid View to another, but the Grid View is not displaying the data in order.
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class PuntoVenta : Page
{
DataTable dtband = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtbind = new DataTable();
dtbind.Columns.Add("Id");
dtbind.Columns.Add("Qnt");
dtbind.Columns.Add("Unit");
dtbind.Columns.Add("Name");
dtbind.Columns.Add("Rel");
dtbind.Columns.Add("Price");
dtbind.Columns.Add("Class");
Session["ss"] = dtbind;
}
}
protected void GridViewA_SelectedIndexChanged(object sender, EventArgs e) {
dtband = (DataTable)Session["ss"];
DataRow dataRow;
dataRow = dtband.NewRow();
int i2 = 0;
for (int i = 0; i < dataRow.Table.Columns.Count; i++)
{
dataRow[i] = GridViewA.SelectedRow.Cells[i2].Text;
i2++;
}
dtband.Rows.Add(dataRow);
GridViewB.DataSource = dtband;
GridViewB.DataBind();
}
}
When I run the code, The GridViewB is populated but its first Column is empty, furthermore, the values that should be displayed in the first column, are displayed in the second column.
You can set DiplayIndex property of Gridview Column,
//Here 1 is index of desired column
datagridview1.Columns["ColumnName"].DisplayIndex = 1;
Add below code in your application
dtbind.Columns.Add("Id");
dtbind.Columns["Id"].DisplayIndex = 0;
dtbind.Columns.Add("Qnt");
dtbind.Columns["Qnt"].DisplayIndex = 1;
//Like onwards
For more info on DisplayIndex property refer This Link
I fill the textboxes on page_load event.Then I edit textboxes data and tried to update data. Variables are assigned with old values. How can I do to get the new values.
Here is my code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class mymembertype : System.Web.UI.Page
{
public static int mem_typeid;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["valueid"] != null)
{
mem_typeid = (int)(Session["valueid"]);
string memtype_name = Convert.ToString(Session["valueName"]);
string rate = Convert.ToString(Session["rate"]);
txtmembtype.Text = Convert.ToString(memtype_name);
txtdscrate.Text = rate;
Insert_membertype.Text = "Update";
}
}
protected void Insert_membertype_Click(object sender, EventArgs e)
{
funtions fun = new funtions();
if (txtmembtype.Text != "" && txtdscrate.Text != "" )
{
if (Insert_membertype.Text == "Save")
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Insert_membertype(membetype, dscrate);
if (chk)
lblInfo.Text = " saving membertype successful";
else
lblInfo.Text = "Error saving membertype";
}
else
{
string membetype = txtmembtype.Text;
int dscrate = Convert.ToInt32(txtdscrate.Text);
bool chk = fun.Update_memberType(mem_typeid, membetype, dscrate);
if (chk)
lblInfo.Text = " Updating membertype successful";
else
lblInfo.Text = "Error Updating membertype";
}
}
}
}
As you see second condition block is for updating data. But it have only values in page load.Now new data is assigned. Please ....
Your problem is that Page Load is called before the event handler for your controls. If you want to understand more about the order things happen in ASP.net just Google "ASP.Net Page Lifecycle" - if you're going to be doing a lot of development I recommend at least getting a basic understanding of what ASP.Net is doing.
You'll want to change your page load to check if the current request is a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && Session["valueid"] != null)
{
// Doing stuff
}
}
The "IsPostBack" variable is false the first time the page is loaded, and then is true for every subsequent load.
Try if(!IsPostBack) method in Pageload event
You need to write the code inside page_load under IsPostback condition like below to get the updated values
if (!IsPostBack)
{
// Bind your code here
}
write a code GetData Method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
}
}
public void GetData()
{
}
thank you for your time.
I'm trying to write the program to filter the value from CSV file. I have three textbox and one datagridview in my form.
So far i managed to parse the CSV into the DataGridView. The problem occur when i trying to filter the value inside the first column by using two value in textbox.
So far, i just managed to selected the row with value given in the Textbox. How can i possibly to filter the datagridview like below:-
Textbox1 value < value in column > Textbox2 value
This is example of my csv files:-
Northing,Easting,Result
645789.900,578778.982,6.78
645782.892,578767.289,5.54
645801.435,579213.430,6.78
645804.156,579445.670,5.79
645980.188,582544.389,8.90
645983.456,582667.344,8.79
646590.253,584788.212,7.60
646800.789,585690.312,2.50
646909.452,585780.212,4.30
647900.323,585890.345,6.89
This is code i using so far:-
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Linq;
using System.ComponentModel;
using DgvFilterPopup;
namespace ZoningParameter
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
void BtnSelectClick(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
// Insert code to read the stream here.
tbxSelectFile.Text = openFileDialog1.FileName;
myStream.Close();
}
}
}
void BtnCancelClick(object sender, EventArgs e)
{
tbxSelectFile.Text = null;
}
void BtnGenerateClick(object sender, EventArgs e)
{
// get all lines of csv file
string[] str = File.ReadAllLines(tbxSelectFile.Text);
// create new datatable
DataTable dt = new DataTable();
// get the column header means first line
string[] temp = str[0].Split(',');
// creates columns of gridview as per the header name
foreach (string t in temp)
{
dt.Columns.Add(t, typeof(string));
}
// now retrive the record from second line and add it to datatable
for (int i = 1; i < str.Length; i++)
{
string[] t = str[i].Split(',');
dt.Rows.Add(t);
}
DataGridValue.DataSource = dt;
}
void BtnFilterClick(object sender, EventArgs e)
{
// create new DataTable
DataTable dt = ((DataTable)DataGridValue.DataSource);
foreach (DataGridViewRow row in DataGridValue.Rows)
{
// Test if the first column of the current row equals
// the value in the text box
if ((String)row.Cells["Northing"].Value == tbxX1.Text)
{
// we have a match
row.Selected = true;
}
else
{
row.Selected = false;
}
}
Can someone show me the right way how to do this? Thank you very much.
EDITED!!!
Thank you therak for your help. This is working code
dv.RowFilter = String.Format("Northing < '{0}' AND Northing > '{1}'",tbxX2.Text, tbxX1.Text)
what you are looking for is a DataView which you can bind to a DataGridView.DataSource.
DataViews can be filtered/sorted etc. For more info about DataView have a loot at this
In your case it will be something like this:
DataView dv = ((DataTable)DataGridValue.DataSource).DefaultView;
dv.RowFilter = "ColumnName < TB1 AND ColumName > TB2"
Afterwards bind the DataView to your gridView
Try Like this
private void button1_Click(object sender, EventArgs e)
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter =
string.Format("Northing = '{0}'", textBox2.Text);
}
try this haven't tested it but might work for your situation:
void BtnFilterClick(object sender, EventArgs e)
{
// create new DataTable
DataTable filteredDataTable = new DataTable();
filteredDataTable.Columns.Add("csv column");
DataTable dt = ((DataTable)DataGridValue.DataSource);
foreach (DataGridViewRow row in DataGridValue.Rows)
{
// Test if the first column of the current row equals
// the value in the text box
if ((String)row.Cells["Northing"].Value == tbxX1.Text)
{
// we have a match
filteredDataTable.Add(row)
}
}
DataGridValue.DataSource = null;
DataGridValue.DataSource = filteredDataTable;
}
Im trying to implement a search function for when the user enters text in a textbox (tbPartNum) and then clicks the "Find" button it then searches the cells in dataGridView1 and once its found it, it highlights the entire row yellow. My code is as follows which obviously doesn't work it throws an error which states:
"NullReferenceException was unhandled"
and underneath it:
"Object reference not set to an instance of an object."
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace GBstock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// populate the dataGridView with the Excel File
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", #"C:\Documents and Settings\rghumra\Desktop\Visual Studio\GBstock\GBstock\bin\Debug\FORM TEST.xlsx");
string query = String.Format("select * from [{0}$]", "Sheet1");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
// populates the comboBox (cbSuppList) with all column headers
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
cbSuppList.Items.Add(col.HeaderText);
}
}
private void btnFind_Click(object sender, EventArgs e)
{
// Code to search the alphanumneric Part Number (in Column1 header called "PART NUMBER") and highlihgt the row
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["PART NUMBER"].Value.ToString().Equals(tbPartNum.Text))
{
dataGridView1.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}
private void fileToolStripMenuItem_Click(object sender, EventArgs e)
{
Instructions instructionForm = new Instructions();
instructionForm.Show();
}
private void partToolStripMenuItem_Click(object sender, EventArgs e)
{
NewPart newPartForm = new NewPart();
newPartForm.Show();
}
private void supplierToolStripMenuItem_Click(object sender, EventArgs e)
{
NewSupplier newSuppForm = new NewSupplier();
newSuppForm.Show();
}
}
}
NullReferenceException you're experiencing most likely comes from the fact that your grid contains null cell values, which get scanned in the foreach of your find handler. Try changing the following line:
if (row.Cells["PART NUMBER"].Value.ToString().Equals(tbPartNum.Text))
To
var cellValue = row.Cells["PART NUMBER"].Value;
if (cellValue != null && cellValue.ToString() == tbPartNum.Text)