net sql server , I want a loop to retrieve data from sql database to different label controls using C# asp.net sql server storedprocedure.
string constrng = ConfigurationManager.ConnectionStrings["baby"].ConnectionString;
SqlConnection conn = new SqlConnection(constrng);
SqlCommand sqlComm;
sqlComm = new SqlCommand("stor_proc", conn);
sqlComm.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
SqlDataReader dr = sqlComm.ExecuteReader();
DataSet ds = new DataSet();
ds.Tables.Add("Home");
ds.Tables[0].Load(dr);
m.Text = ds.Tables[0].Rows[0][1].ToString();
i.Text = ds.Tables[0].Rows[0][2].ToString();
d.Text = ds.Tables[0].Rows[0][3].ToString();
g.Text = ds.Tables[0].Rows[0][4].ToString();
m1.Text = ds.Tables[0].Rows[1][1].ToString();
i1.Text = ds.Tables[0].Rows[1][2].ToString();
d1.Text = ds.Tables[0].Rows[1][3].ToString();
g1.Text = ds.Tables[0].Rows[1][4].ToString();
m2.Text = ds.Tables[0].Rows[2][1].ToString();
i2.Text = ds.Tables[0].Rows[2][2].ToString();
d2.Text = ds.Tables[0].Rows[2][3].ToString();
g2.Text = ds.Tables[0].Rows[2][4].ToString();
conn.Close();
for (int i = 0; i < 3; i++ ) {
m.Text = ds.Tables[0].Rows[i][1].ToString();
i.Text = ds.Tables[0].Rows[i][2].ToString();
d.Text = ds.Tables[0].Rows[i][3].ToString();
g.Text = ds.Tables[0].Rows[i][4].ToString();
}
You can use a foreach loop like this:
foreach (DataRow row in ds.Tables[0].Rows)
{
// Now here, you are iterating through a individual row.
// ItemArray gives an index position of a cell within a row.
m.Text = row.ItemArray[0].ToString();
i.Text = row.ItemArray[1].ToString();
d.Text = row.ItemArray[2].ToString();
g.Text = row.ItemArray[3].ToString();
}
Related
im getting only 1 row multiple times instead of getting multiple records. same record getting multiple times in the datatable and model.
List<Trans_energycons_ReportModel> model = new List<Trans_energycons_ReportModel>();
using (SqlConnection con = new SqlConnection("constr"))
{
con.Open();
SqlCommand cmd_get_transformer_consumption = new SqlCommand(#"SELECT
Date,units from Total_Power", con);
SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
DataTable dt = new DataTable();
da_get_trans_consumption.Fill(dt);
Trans_energycons_ReportModel m = new Trans_energycons_ReportModel();
foreach (DataRow row in dt.Rows)
{
string deviceDate = row["Date"].ToString();
string units = row["units"].ToString();
m.DeviceDate =Convert.ToDateTime(deviceDate);
m.Units =Convert.ToDouble(units);
model.Add(m);
}
}
return View(model);
Since the object is created before foreach, The object will be replaced with new entries all the time. Add Trans_energycons_ReportModel m = new Trans_energycons_ReportModel(); inside foreach
List<Trans_energycons_ReportModel> model = new List<Trans_energycons_ReportModel>();
using (SqlConnection con = new SqlConnection("constr"))
{
con.Open();
SqlCommand cmd_get_transformer_consumption = new SqlCommand(#"SELECT Date,units from Total_Power", con);
SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
DataTable dt = new DataTable();
da_get_trans_consumption.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string deviceDate = row["Date"].ToString();
string units = row["units"].ToString();
//Create object here
Trans_energycons_ReportModel m = new Trans_energycons_ReportModel();
m.DeviceDate = Convert.ToDateTime(deviceDate);
m.Units = Convert.ToDouble(units);
model.Add(m);
}
}
return View(model);
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'm trying to set values on items in combobox, but everytime I try so I get the result 'null'. Am I defining the value wrong or am I trying to get the value in a wrong way?
// Setting the value
sqlCmd.CommandText = "SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0";
conn.Open();
using (var reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
cmbUnajmljivaci.Items.Add(new { Id = reader["Id"].ToString(), Ime = reader["Ime"].ToString() });
}
cmbUnajmljivaci.ValueMember = "Id"; // <---
cmbUnajmljivaci.DisplayMember = "Ime";
}
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(cmbUnajmljivaci.SelectedValue));
using (SqlConnection sqlConn = new SqlConnection("CONNECTION STRING"))
{
DataSet ds = new DataSet();
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlConn.Open();
SqlDataAdapter SQA_DataAdapter = new SqlDataAdapter(sqlCmd);
SQA_DataAdapter.SelectCommand = new SqlCommand("SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0", sqlConn);
SQA_DataAdapter.Fill(ds, "Table");
if (ds != null)
if (ds .Tables.Count > 0)
{
cmbUnajmljivaci.ValueMember = "Id";
cmbUnajmljivaci.DisplayMember = "Ime";
cmbUnajmljivaci.DataSource = ds.Tables[0];
}
sqlConn.Close();
}
You need to set the data source of the combobox.
Try getting the Value like this:
dynamic dyn = cmbUnajmljivaci.SelectedItem;
string s = dyn.Id;
Or even inline like this:
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(((dynamic)cmbUnajmljivaci.SelectedItem).Id);
Sample Code for Reference to your problem,
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add("0", "Item1");
dt.Rows.Add("1", "Item2");
For inserting the item with specified index you need to use the below code
//Insert the item into the collection with specified index
foreach (DataRow row in dt.Rows)
{
int id = Convert.ToInt32(row["ID"]);
string name=row["Name"].ToString();
comboBox1.Items.Insert(id,name);
}
Always index should start from 0 (Zero).
Easy way to add values to combobox
comboBox1.DataSource=dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
I tried bind the DataGridView from Table "NatureCharge"
private void BindGrid()
{
DataGridViewNatureCharge.DataSource = null;
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("select * from NatureCharge", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
DataGridViewNatureCharge.DataSource = dt;
}
}
}
}
}
But I need to show Nom Famille not the Id, so what is the modification on select query???
"select * from NatureCharge where Idfam =(select NomFam from Famille)"
Update
the problem with NomFam created in another cell in DatagridView.
I need to add it in 3rd cell.
select n.IdNat,n.NomNat,f.NomFam from NatureCharge n join Famille f on n.IdFam=f.IdFam
The DataGridView
//Set Columns Count
DataGridViewNatureCharge.ColumnCount = 3;
//Hide the last blank line
DataGridViewNatureCharge.AllowUserToAddRows = false;
//Add Columns
DataGridViewNatureCharge.Columns[0].Name = "IdNat";
DataGridViewNatureCharge.Columns[0].HeaderText = "N° Nature de Charge";
DataGridViewNatureCharge.Columns[0].DataPropertyName = "IdNat";
DataGridViewNatureCharge.Columns[0].Width = 100;
DataGridViewNatureCharge.Columns[1].HeaderText = "Nom de Nature de Charge";
DataGridViewNatureCharge.Columns[1].Name = "NomNat";
DataGridViewNatureCharge.Columns[1].DataPropertyName = "NomNat";
DataGridViewNatureCharge.Columns[1].Width = 150;
DataGridViewNatureCharge.Columns[2].Name = "IdFam";
DataGridViewNatureCharge.Columns[2].HeaderText = "Nom de Famille";
DataGridViewNatureCharge.Columns[2].DataPropertyName = "IdFam";
DataGridViewNatureCharge.Columns[2].Width = 100;
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "";
checkBoxColumn.Width = 30;
checkBoxColumn.Name = "checkBoxColumn";
DataGridViewNatureCharge.Columns.Insert(0, checkBoxColumn);
Use SQL joins for this.
SELECT A.NomFam, B.IdNat, B.NomNat FROM Famille A join NatureChange B on A.IdFam = B.IdFam
I put my all code and trying to create a dynamic chart which series comes from database,i looped through listitem collection and trying to populate series and add to the chart.However even i loop through ("#Plant2", DT.Rows[i][0].ToString()); Plant2 and trying to populate multiple series with
plantseries = DT.Rows[i][0].ToString();
Chart1.Series.Add(plantseries);
and then give series the X and Y valuemembers.Finally i can not get all the series in my chart,result indicates last same values for all items in the loop,like my code overwrites the last value onto the same series name.Please help me,i am lost.
string[] lstBox = HiddenField2.Value.Split(seperator, StringSplitOptions.RemoveEmptyEntries);
ListItemCollection lstItemCollection = new ListItemCollection();
for (int i = 0; i < lstBox.Length; i++)
{
lstItemCollection.Add(new ListItem(lstBox[i]));
}
DataTable DT = new DataTable();
DT.Columns.Add("Plant");
foreach (ListItem item in lstItemCollection)
{
DataRow dr = DT.NewRow();
dr["Plant"] = item.Value;
DT.Rows.Add(dr);
}
String plantseries = "";
Chart1.Legends.Add("Plants");
LegendItem legendItem = new LegendItem();
for (int i = 0; i < lstItemCollection.Count; i++)
{
DataTable monthlychart = new DataTable();
if (cnn.State == ConnectionState.Closed)
{
cnn.Open();
SqlCommand cmd1 = new SqlCommand("prc_Chart_individual_plant", cnn);
cmd1.CommandType = System.Data.CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#Plant", strPlants.ToString());
cmd1.Parameters.AddWithValue("#Configuration", strconfig.ToString());
cmd1.Parameters.AddWithValue("#Startdate", dtstart);
cmd1.Parameters.AddWithValue("#Enddate", dtend);
cmd1.Parameters.AddWithValue("#Plant2", DT.Rows[i][0].ToString());
SqlDataAdapter adapt1 = new SqlDataAdapter(cmd1);
adapt1.Fill(monthlychart);
Chart1.DataSource = monthlychart;
cnn.Close();
}
plantseries = DT.Rows[i][0].ToString();
Chart1.Series.Add(plantseries);
Chart1.Series[plantseries].XValueMember = Convert.ToString(monthlychart.Columns[4]);
Chart1.Series[plantseries].YValueMembers = Convert.ToString(monthlychart.Columns[8]);
Chart1.DataBind();
legendItem.Name = plantseries;
legendItem.BorderWidth = 4;
legendItem.ShadowOffset = 1;
Random random = new Random();
Color c = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
legendItem.Color = c;
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "M.yy";
Chart1.Series[plantseries].IsVisibleInLegend = true;
Chart1.Series[plantseries].IsValueShownAsLabel = true;
Chart1.Series[plantseries].ToolTip = "Data Point Y Value: #VALY{G}";
}
This is the best approac and it works
for(int j=0; j<monthlychart.Rows.Count; j++)
{
if(monthlychart.Rows[j][4]!=DBNull.Value)
{
DateTime xvalue = Convert.ToDateTime(monthlychart.Rows[j][4]);
double yvalue = Convert.ToDouble(monthlychart.Rows[j][8]);
Chart1.Series[plantseries].Points.AddXY(xvalue,yvalue);
Chart1.DataBind();
}
}