How to display calculated value in gridview? - c#

Here I am getting the values to my grid. This is Connection of my database table. It is okay and working well but i want to show my Qty field data by dividing my txtOrderQuantity (textbox id name)value.
<asp:TextBox ID="txtOrderQuantity" runat="server"
ontextchanged="txtOrderQuantity_TextChanged" AutoPostBack="true"> </asp:TextBox>
How i can show my grid view field by dividing by 2 with txtorderQuantity.
public DataTable GetData()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
SqlDataAdapter sa = new SqlDataAdapter();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [RmId],[RmName],[MeasuringUnit],[Rate],[Qty],[BagSz]FROM [dbo].[RawMaterials]",con);
sa.SelectCommand = cmd;
sa.Fill(dt);
con.Close();
return dt;
}

you can do it two ways.
1) you can send the value of the text field to your GetData() method. and then prepare your select statement in the following way
public DataTable GetData(int OrderQuantity)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
SqlDataAdapter sa = new SqlDataAdapter();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [RmId],[RmName],[MeasuringUnit],[Rate],([Qty]/OrderQuantity )as Qty,[BagSz]FROM [dbo].[RawMaterials]",con);
sa.SelectCommand = cmd;
sa.Fill(dt);
con.Close();
return dt;
}
2) you can use RowDataBound Event of GridView. it occurs when a single DataRow have bound in the gridView.
void YourGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Display the company name in italics.
// I assume the index of Qty column is 4
e.Row.Cells[4].Text = decimal.Parse(e.Row.Cells[4].Text)/decimal.Parse(txtOrderQuantity.Text) ;
}
}

Use RowDataBound event of gridview and perform following steps:
Find the textbox control and its value.
Find the MyQty value and divide it with textbox value(use specific type cast wherever needed.)
Find your control to display MyQty valud and assign calculated value.

Related

c# asp.net Index was out of range. when I trying to select a row

I have a gridview on my page. And I have 2 snippets of SQL code to binds that gridview.
First one is run on page load. If there are records returned from the first SQL, I can select a row on gridview.
But the problem is when there is no record returned from the first SQL, I have button that runs another SQL and binds its result to the gridview too. But when I try to select a row, I get this error:
Index was out of range. when I trying to select a row Must be non-negative and less than the size of the collection. Parameter name: index
My code is like that
First SQL (its run on page load)
void listele()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar where durum='Çözülmedi' or durum='İşlem Yapılıyor'", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
baglanti.Close();
}
and thats the second SQL that when runs when I click button
void listelehepsi()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
baglanti.Close();
}
and this is the GridView1_SelectedIndexChanged event
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int secili;
secili = GridView1.SelectedIndex;
GridViewRow row = GridView1.Rows[secili]; // I GOT ERROR HERE
TextBox1.Text = row.Cells[1].Text;
}
why Am I getting this error ?
EDIT--
I got solve changing the page load sql like this;
void listele()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar where durum='Çözülmedi' or durum='İşlem Yapılıyor'", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
if (!IsPostBack)
{
GridView1.DataBind();
}
else
{
//
}
baglanti.Close();
}
Make sure that you are not rebinding your datagrid on postback - you can do this in your PageLoad event - something like
if (!IsPostback)
{
... bind your datagrid
}
In the GridView1_SelectedIndexChanged event, could you simply do a RowCount to see if the value is != 0 before the other code runs?
if (GridView1.RowCount <= 0)
{
return;
}

How To count updated same record row in db and show count number in label?

Here i have table name tblbb which have a column called journalname, textbox ,button and a label.I have store some data in tblbb. Now what i am trying to do is, to count same data row in column journalname when i input data data in textbox and on button click show the count in label.
for eg in tblbb
Journalname
a
a
b
b
if textbox.text="a"
label.text=2
But the problem is that when i update data in table the label text does not show the updated count for that data.For example if i store one more a in above table then on button click the must show lable.text=3,but instead of that it shows label.text=2 even the table is updated.
The method used
public DataTable getjournalcount(string journalname)
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
string sql = "select journalname, count(*) as dupes from tblbb group by journalname";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#JournalName", journalname);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
Code behind button
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = j.getjournalcount(TextBox1.Text);
if (dt.Rows.Count>0)
{
Label1.Text= dt.Rows[0]["dupes"].ToString();
}
}
modify your sql as
string sql = "select journalname, count(*) as dupes
from tblbb where where journalname=#journalname
group by journalname";

Display data in datagridview table with select statement

I want to know how to populate a DataGridView with information found from a Select statement. Here's my event for the select button:
private void SelectCust(object sender, EventArgs e)
{
OleDbConnection conn = null;
conn = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0; " + "Data Source=" + "c:/inetpub/ftproot/ora103/App_Data/Fashion.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * from Customer where CustNum = #MyCust ", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
DataTable dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataBind();
if (dt.Rows.Count > 0)
{
}
conn.Close();
}
I want to use the "if" statement to insert information I've gathered from my Customers table, and populate a DataGridView. However, I'm having trouble connecting the DataGridView to my Microsoft Access Database (called Fashion.accdb). Here's what my DataGridView looks like as of now (I know it's not much):
<asp:GridView ID="dataGridView1" runat="server" EnableModelValidation="True">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
EDIT
Here's the error :
Exception Details: System.Data.OleDb.OleDbException: No value given
for one or more required parameters.
The idea is that I'll be typing in a customer number into a textbox. Then I'll hit the submit button. Then the event will retrieve that number from the textbox that was typed in, grab the information in the database pertaining to that customer, and display it in a GridView
oledb parameters are different than sql server's.
...where CustNum = #MyCust
needs to be
...where CustNum = ? (or: where CustNum = [?])
after setting the adapter's command, set the parameter(s):
cmd.Parameters.Add("#CustNum", OleDbType.Integer, 15).Value = yourValue;
hope that helps.

combobox /dropdownlist in grid view c#.net

I am a newbie to c#.net winforms application. I have a data grid wch displays some data and out of which one of the column shud be made a dropdownlist or combobox. how do I use that in my code. please help.
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
DataGridViewComboBoxColumn combo = (DataGridViewComboBoxColumn)dataGridView1.Rows[e.RowIndex].Cells[3].OwningColumn;
sql = "select NAME FROM Suppliers";
BindingSource bsource = new BindingSource();
bsource.DataSource = obj.SqlDataTable(sql);
dataGridView1.DataSource = bsource;
combo.HeaderText = "Select Supplier";
}
I want to populate the 3rd column of the data grid with supplier name from the corresponding suppliers table.The data grid view is already populated with data from a join query and one of the field is Supplier(wch I mwant to convert to a dropdown or combo box). let me know if you need any further info for clarifications.
I Modified my code as follows:
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Suppliers";
//execute sql data adapter to get supplier values
DataTable dt = obj.SqlDataTable("select NAME from CUSTOMERS");
foreach (DataRow supplier in dt.DataSet.Tables[0].Rows)
{
combo.Items.Add(supplier[0]);
}
dataGridView1.Columns.Add(combo);
now am getting a null reference exception at " dt.DataSet.Tables[0].Rows"
. plz help. I am not sure if am missing something.
Try this code
string strcon = #"Data Source=kp;Initial Catalog=Name;Integrated Security=True;Pooling=False";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataGridViewComboBoxColumn dgvCmb;
public Form2()
{
InitializeComponent();
grdcmd();
}
public void grdcmd()
{
con = new SqlConnection(strcon);
con.Open();
string qry = "Select * from Dbname";
da = new SqlDataAdapter(qry, strcon);
dt = new DataTable();
da.Fill(dt);
dgvCmb = new DataGridViewComboBoxColumn();
foreach (DataRow row in dt.Rows)
{
dgvCmb.Items.Add(row["Fname"].ToString());
}
dataGridView1.Columns.Add(dgvCmb);
}

Send data from class to winform

I am developing an application using Winforms and C#. I have a class which will fetch master data of one table. The function in the class executes a stored procedure which returns 2 columns of data.
I have one form, which has a Listbox control, TextBox and ComboBox. I would like to:
Display entire data for column 1 on List box.
Display column 1 selected row value on Textbox and column 2 value in Combo Box for the selected row. Value changes based on selection change in Listbox.
Code to get data using the stored procedure:
public void GetDeity()
{
cmd = new SqlCommand();
cmd.Connection = conDB;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "get_DeityMaster";
cmd.ExecuteNonQuery();
return;
}
ListBox Name: lstDeityList
TextBox Name: txtDeityName
ComboBox Name: cmbDeityCategoryName
Please help on how to pass data. Thanks
you need to return data from your method like below, currently your method return nothing.
you may need to change the method implementation to return DataTable or DataSet
public DataTable GetDeity()
{
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand("get_DeityMaster", sqlConn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
Now you can bind the Listbox control using returned datatable above, when selected item change event you can bind other text box and combo boxes.
in your Form you can call the class method by creating object of class like below
Yourclass obj = new Yourclass();
DataTable dt= obj.GetDeity();
ListBox1.DataSource = dt;
ListBox1.DisplayMember = "Column1Name";
ListBox1.ValueMember = "Column2Name";
You need to add SelectedIndexChanged event for the ListBox1
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
TextBox1.Text = ((DataRowView)ListBox1.SelectedItem).Row.ItemArray[0].ToString();
// bind the ComboBox as well
}
Change return type of function from void to DataTable. Create SQLAdapter with your command and fill DataTable.
public DataTable GetDeity()
{
DataTable mTable = new DataTable();
cmd = new SqlCommand();
cmd.Connection = conDB;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "get_DeityMaster";
SqlAapter mAdapter = new SqlAdapter(cmd);
mAdapter.Fill(mTable);
return mTable
}
Why don't you hold the fetched data in a datatable. Then assign columns of that datatable to different controls you like.
e.g.
public void GetData()
{
DataTable odt = new DataTable();
odt = obj.GetDeity();
Combobox.DataSource = odt;
.......... set other controls also...
}
public DataTable GetDeity()
{
SqlCommand cmd = new SqlCommand("get_DeityMaster");
cmd.CommandType = CommandType.StoredProcedure;
return getdatatable(cmd); // YOUR DATA FETCHING LOGIC
}

Categories