I have some problem with coding on C# with data from dataGridView.
I have some data table on dataGridView and I need to put this info into gMapControl using GMap.Net for creating of several markers on the map.
Here is my code:
private void gMapControl1_Load(object sender, EventArgs e)
{
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
GMap.NET.WindowsForms.GMapOverlay markersOverlay = new GMap.NET.WindowsForms.GMapOverlay(gMapControl1, "marker");
GMap.NET.WindowsForms.Markers.GMapMarkerGoogleGreen marker =
new GMap.NET.WindowsForms.Markers.GMapMarkerGoogleGreen(
new GMap.NET.PointLatLng(MyVar.lat, MyVar.lon));
gMapControl1.Position = new GMap.NET.PointLatLng(MyVar.lat, MyVar.lon);
marker.ToolTip = new GMap.NET.WindowsForms.ToolTips.GMapRoundedToolTip(marker);
marker.ToolTipText = "Home";
markersOverlay.Markers.Add(marker);
gMapControl1.Overlays.Add(markersOverlay);
}
This is pseudo code, that should get you going
var dgv = new DataGridView();
var str = dgv.Rows[0].Cells["Column Name here"]; //column name
var ord = dgv.Rows[0].Cells[0]; //column ordnal
var changeableValue = string.Empty;
foreach (DataGridViewRow row in dgv.Rows)
{
changeableValue = row.Cells[0].ToString(); // ordinal position again
}
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
GMapControl1.DragButton = Windows.Forms.MouseButtons.Left
GMapControl1.CanDragMap = True
If RadioButton1.Checked Then
' Form3.GMapControl1.MapProvider = GMapProviders.GoogleSatelliteMap
Form3.GMapControl1.MapProvider = GMapProviders.GoogleHybridMap
ElseIf RadioButton2.Checked Then
Form3.GMapControl1.MapProvider = GMapProviders.GoogleMap
ElseIf RadioButton3.Checked Then
Form3.GMapControl1.MapProvider = GMapProviders.GoogleTerrainMap
End If
Form3.GMapControl1.Position = New PointLatLng(35.502509, 2.916693)
Form3.GMapControl1.MinZoom = 0
Form3.GMapControl1.MaxZoom = 24
Form3.GMapControl1.Zoom = 7
Form3.GMapControl1.Dock = DockStyle.Fill
'GMapControl1.AutoScroll = True
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerAndCache
For j As Integer = 0 To DataGridView1.Rows.Count - 2
Dim marker As GMarkerGoogle = New GMarkerGoogle(New PointLatLng(DataGridView1.Rows(j).Cells(1).Value, DataGridView1.Rows(j).Cells(2).Value), GMarkerGoogleType.green)
' marker.ToolTipText = String.Format("réservoir " + DataGridView1.Rows(j).Cells(4).Value)
marker.ToolTipText = String.Format("Réservoir " + DataGridView1.Rows(j).Cells(8).Value + " m3 " + DataGridView1.Rows(j).Cells(4).Value)
markers.Markers.Add(marker)
Form3.GMapControl1.Overlays.Add(markers)
marker.ToolTipMode = MarkerTooltipMode.Always
Next
Return
End Sub
Related
This is my code which return me attribute values in the selected block,
but I want these values in a table to show on the dwg file. And the text must be single mtext object.
[CommandMethod("NLTAB")]
public void ListAttributes()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Editor ed = acDoc.Editor;
Database db = acDoc.Database;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
try
{
TypedValue[] filList = new TypedValue[2] { new TypedValue((int)DxfCode.Start, "INSERT"), new TypedValue((int)DxfCode.HasSubentities, 1) };
SelectionFilter filter = new SelectionFilter(filList);
PromptSelectionOptions opts = new PromptSelectionOptions();
opts.MessageForAdding = "Select block references: ";
PromptSelectionResult res = ed.GetSelection(opts, filter);
// Do nothing if selection is unsuccessful
if (res.Status != PromptStatus.OK)
return;
SelectionSet selSet = res.Value;
ObjectId[] idArray = selSet.GetObjectIds();
PromptPointResult ppr;
PromptPointOptions ppo = new PromptPointOptions("");
ppo.Message = "\n Select the place for print output:";
//get the coordinates from user
ppr = ed.GetPoint(ppo);
if (ppr.Status != PromptStatus.OK)
return;
Point3d startPoint = ppr.Value.TransformBy(ed.CurrentUserCoordinateSystem);
Vector3d disp = new Vector3d(0.0, -2.0 * db.Textsize, 0.0);
TextStyleTable ts = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead);
ObjectId mtStyleid = db.Textstyle;
if (ts.Has("NAL-TEXT"))
{
mtStyleid = ts["NAL-FORMAT"];
}
var curSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
MText _outputHeading = new MText();
_outputHeading.Location = startPoint;
_outputHeading.Width = 75.207;
_outputHeading.Height = 1.488;
_outputHeading.TextStyleId = mtStyleid;
string file = acDoc.Name;
string str1 = Path.GetFileNameWithoutExtension(file);
//string str1 = ("534-W10A-R1");
//var curSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
Match match = Regex.Match(str1, #"^(\w+-[CSDWM]\d+[A-Z]-.)$");
var pattern = #"^(\d+)-[A-Z](\d+)([A-Z])-";
var groups = Regex.Match(str1, pattern).Groups;
var _projectCode = groups[1].Value;
var _phaseCode = _projectCode + "-" + groups[2].Value;
var _zoneCode = _phaseCode + groups[3].Value;
curSpace.AppendEntity(_outputHeading);
tr.AddNewlyCreatedDBObject(_outputHeading, true);
db.TransactionManager.QueueForGraphicsFlush();
startPoint += disp;
HashSet<string> attValues = new HashSet<string>();
foreach (ObjectId blkId in idArray)
{
BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead);
BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForWrite);
AttributeCollection attCol = blkRef.AttributeCollection;
foreach (ObjectId attId in attCol)
{
AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForRead);
string str = (attRef.TextString);
string tag = attRef.Tag;
if (attValues.Contains(str))
continue;
if (btr.Name == "NAL-TAG crs ref")
{
var curSpace1 = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
MText mtext = new MText();
mtext.Location = startPoint;
mtext.Contents = tag.ToString() + " : " + str + "\n";
//ed.WriteMessage(text);
curSpace.AppendEntity(mtext);
tr.AddNewlyCreatedDBObject(mtext, true);
db.TransactionManager.QueueForGraphicsFlush();
attValues.Add(str);
startPoint += disp;
}
}
}
tr.Commit();
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
ed.WriteMessage(("Exception: " + ex.Message));
}
}
}
To crate a table, at this blog post, you'll find a sample code in C# that should work for you. The result should look like the image below.
And here is the source code. After creating the table, if you really need the texts, you can call .Explode() on it and extract all the text entities.
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
namespace TableCreation
{
public class Commands
{
[CommandMethod("CRT")]
static public void CreateTable()
{
Document doc =
Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
PromptPointResult pr =
ed.GetPoint("\nEnter table insertion point: ");
if (pr.Status == PromptStatus.OK)
{
Table tb = new Table();
tb.TableStyle = db.Tablestyle;
tb.NumRows = 5;
tb.NumColumns = 3;
tb.SetRowHeight(3);
tb.SetColumnWidth(15);
tb.Position = pr.Value;
// Create a 2-dimensional array
// of our table contents
string[,] str = new string[5, 3];
str[0, 0] = "Part No.";
str[0, 1] = "Name ";
str[0, 2] = "Material ";
str[1, 0] = "1876-1";
str[1, 1] = "Flange";
str[1, 2] = "Perspex";
str[2, 0] = "0985-4";
str[2, 1] = "Bolt";
str[2, 2] = "Steel";
str[3, 0] = "3476-K";
str[3, 1] = "Tile";
str[3, 2] = "Ceramic";
str[4, 0] = "8734-3";
str[4, 1] = "Kean";
str[4, 2] = "Mostly water";
// Use a nested loop to add and format each cell
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
tb.SetTextHeight(i, j, 1);
tb.SetTextString(i, j, str[i, j]);
tb.SetAlignment(i, j, CellAlignment.MiddleCenter);
}
}
tb.GenerateLayout();
Transaction tr =
doc.TransactionManager.StartTransaction();
using (tr)
{
BlockTable bt =
(BlockTable)tr.GetObject(
doc.Database.BlockTableId,
OpenMode.ForRead
);
BlockTableRecord btr =
(BlockTableRecord)tr.GetObject(
bt[BlockTableRecord.ModelSpace],
OpenMode.ForWrite
);
btr.AppendEntity(tb);
tr.AddNewlyCreatedDBObject(tb, true);
tr.Commit();
}
}
}
}
}
I have a DataGridView which i am populating as shown below.This DataGridView has 7 columns, where 1st, 4th & 6th columns respectively would be unbound and the rest would be bound columns.Now my requirement is
1] In column[0], i want to show an autoincrement integer value like "Serial No." 1,2,3.....n
2] At column[4], i want to show an icon/image from an imagelist.
3] At column[6], i want to show a Button control
try
{
using (FbConnection conLLV = new FbConnection(connectionString))
{
conLLV.Open();
using (FbCommand cmdLLV = new FbCommand(sqlQryLLV, conLLV))
{
cmdLLV.Parameters.Add("#t_id", FbDbType.Integer).Value = tid;
cmdLLV.Parameters.Add("#mem_id", FbDbType.Integer).Value = mid;
cmdLLV.CommandType = CommandType.Text;
using (FbDataAdapter daLLV = new FbDataAdapter(cmdLLV))
{
using (DataTable dtLLV = new DataTable())
{
daLLV.Fill(dtLLV);
dgSSW.AutoGenerateColumns = false;
dgSSW.ColumnCount = 7;
//At Column[0] ->a Serial No column
dgSSW.Columns[1].Name = "subsec_name";
dgSSW.Columns[1].HeaderText = "Sub Section Name";
dgSSW.Columns[1].DataPropertyName = "subsec_name";
dgSSW.Columns[2].Name = "rt_correct_ans";
dgSSW.Columns[2].HeaderText = "Correct Answer";
dgSSW.Columns[2].DataPropertyName = "rt_correct_ans";
dgSSW.Columns[3].Name = "rt_your_ans";
dgSSW.Columns[3].HeaderText = "Your Answer";
dgSSW.Columns[3].DataPropertyName = "rt_your_ans";
//At Column[4] ->an Image column
dgSSW.Columns[5].Name = "q_r_difficulty";
dgSSW.Columns[5].HeaderText = "Difficulty Level";
dgSSW.Columns[5].DataPropertyName = "q_r_difficulty";
//At Column[6] ->a column having a Button control
dgSSW.DataSource = dtLLV;
}//data table closed and disposed here
}// data adapter closed and disposed up here
}// command disposed here
}//connection closed and disposed here
}
catch (FbException ex)
{
MessageBox.Show("LLV--" + ex.Message);
}
How can i achieve my requirements please advise using codes.I have searched the internet but the solutions given does not match my requirements.
possible solution by steps:
0] set datasource
dgSSW.DataSource = dtLLV;
1] row numbers: add column for them and apply cell formatting
var col0 = new DataGridViewTextBoxColumn
{
HeaderText = "#", Name="RowNum",
ReadOnly = true,
Width = 10
};
dgSSW.Columns.Insert(0, col0);
dgSSW.CellFormatting += GridCellFormatting;
private void GridCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dgSSW.Columns[e.ColumnIndex].Name == "RowNum")
{
e.Value = (e.RowIndex + 1).ToString();
}
}
2] image column:
var col3 = new DataGridViewImageColumn { HeaderText = "Pic", Name = "Pic" };
dgSSW.Columns.Insert(4, col3);
// set image for a cell
dgSSW["Pic", 0].Value = Resources.add;
3] buttons column with clicks handling
var col7 = new DataGridViewButtonColumn
{
HeaderText = "Proceed", Name = "Action",
Text = "+",
UseColumnTextForButtonValue = true
};
dgSSW.Columns.Add(col7);
dgSSW.CellContentClick += GridCellContentClick;
private void GridCellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dgSSW.Columns[e.ColumnIndex].Name == "Action")
{
MessageBox.Show((e.RowIndex + 1).ToString());
}
}
update: since you don't use AutoGenerateColumns and create all columns manually, you can create all col0, col3, col7 and after that set DataSource
I am trying to generate a chart for a powerpoint slide using C#.net. The chart works perfectly when I hard code the data, so my goal here is to be able to populate the excel backend from my applications datatable. What i need help with is defining the data ranges(see below)
var areaworkbook = (EXCEL.Workbook)areachart.ChartData.Workbook;
areaworkbook.Windows.Application.Visible = false;
var dataSheet2 = (EXCEL.Worksheet)areaworkbook.Worksheets[1];
var sc2 = areachart.SeriesCollection();
dataSheet1.Cells.Range["A2"].Value2 = "Name 1";
dataSheet1.Cells.Range["A3"].Value2 = "Name 2";
dataSheet1.Cells.Range["A4"].Value2 = "Name 3";
dataSheet1.Cells.Range["A5"].Value2 = "Name 4";
dataSheet1.Cells.Range["B2"].Value2 = Value 1;
dataSheet1.Cells.Range["B3"].Value2 = value 2;
dataSheet1.Cells.Range["B4"].Value2 = value 3;
dataSheet1.Cells.Range["B5"].Value2 = value 4 ;
var series2 = sc2.NewSeries();
series2.Name = "Series 2";
series2.XValues = "'Sheet1'!$A$2:$A$5";
series2.Values = "'Sheet1'!$C$2:$C$5";
series2.ChartType = Office.XlChartType.xlAreaStacked;
areachart.HasTitle = true;
areachart.ChartTitle.Font.Bold = true;
areachart.ChartTitle.Font.Italic = true;
areachart.ApplyLayout(4);
areachart.Refresh();
How will I dynamically add A6, A7, A8... until my datatable is complete?
Just use a loop and calculate the cell address. For the sake of argument, I'm going to assume the data is coming from a Linq query, though you could get it any other way.
int row = 2; // You expect to start here
foreach (var data in db.MyData().Where(... whatever you need here ...))
{
dataSheet1.Cells.Range["A" + row].Value2 = data.Name;
dataSheet1.Cells.Range["B" + row].Value2 = data.Value;
row++;
}
series2.XValues = "'Sheet1'!$A$2:$A$" + row;
series2.Values = "'Sheet1'!$C$2:$C$" + row;
i'm in a trouble!
I'm generating a lot of gridviews dinamically, with dinamic values to columns.
The columns are ever the same.
I want to know how can i set the size of this columns.
That's my code, with my effort.
private void generateControls( List<List<DataRow>> grids)
{
DataTable dt = new DataTable();
int i = 0;
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.Width = new Unit("100%");
//grv.RowStyle.Wrap = false;
grv.RowStyle.Width = new Unit("100%");
grv.ID = "grid_view" + i;
grv.DataSource = dt;
grv.DataBind();
/* grv.Columns[0].ItemStyle.Width = new Unit("5%");
grv.Columns[1].ItemStyle.Width = new Unit("7%");
grv.Columns[2].ItemStyle.Width = new Unit("12%");
grv.Columns[3].ItemStyle.Width = new Unit("12%");
grv.Columns[4].ItemStyle.Width = new Unit("7%");
grv.Columns[5].ItemStyle.Width = new Unit("7%");
grv.Columns[6].ItemStyle.Width = new Unit("23%");
grv.Columns[7].ItemStyle.Width = new Unit("22%");
grv.Columns[8].ItemStyle.Width = new Unit("5%");*/
Label lblBlankLines = new Label();
lblBlankLines.Text = "<br />";
Panel panelGrid = new Panel();
panelGrid.ID = "panel_grid" + i;
Label lblTipo = new Label();
string tipoOcorrencia = lst[0]["Ocorrência"].ToString();
/*
* Capitalized
* TextInfo myTI = new CultureInfo("pt-BR", false).TextInfo;
string novoTipoOcorrencia = myTI.ToTitleCase(tipoOcorrencia);*/
int quantidade = lst.Count;
lblTipo.Text = " - " + tipoOcorrencia + ": " + quantidade;
LinkButton lkBtn = new LinkButton();
lkBtn.ID = "link_button" + i;
lkBtn.Text = "Exibir | Ocultar";
lkBtn.Attributes["onClick"] = "javascript:return ocultaGrid('" + panelGrid.ID + "'), false";
panel_status.Controls.Add(lblBlankLines);
panel_status.Controls.Add(lkBtn);
panel_status.Controls.Add(lblTipo);
panelGrid.Controls.Add(grv);
panel_status.Controls.Add(panelGrid);
panel_status.DataBind();
i++;
}
}
I've tried to get the columns, but i got an error, telling me an invalid index access.
How can i access my columns in that gridview?
Use the RowDataBound EventHandler:
Count your indexes and make sure you are not trying to access a non-existent column as well.
See link for an example:
http://msdn.microsoft.com/en-us/library/ms178296(v=vs.100).ASPX
grv.RowDataBound += grv_RowDataBound;
private void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Width = new Unit("5%");
e.Row.Cells[1].Width = new Unit("7%");
e.Row.Cells[2].Width = new Unit("12%");
e.Row.Cells[3].Width = new Unit("12%");
e.Row.Cells[4].Width = new Unit("7%");
e.Row.Cells[5].Width = new Unit("7%");
e.Row.Cells[6].Width = new Unit("23%");
e.Row.Cells[7].Width = new Unit("22%");
e.Row.Cells[8].Width = new Unit("5%");
}
}
hey guys i am making an art website for my fiance but cant get the images to display and i am doing it exactly like in previews websites i made but using visual studio 2012 from 2008. Here is the code. I get the error sign in the image and not the correct image. It loads the path from the database witch is Art/1.jpg.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Home : System.Web.UI.Page
{
int Add = 1;
protected void Page_Init(object sender, EventArgs e)
{
Database s = new Database();
int Total = s.ArtCount(); //Count the total of cars int the database
for (int loop = Total; loop > 0; loop--)
{
Panel Panel1 = new Panel(); //Create a new panel for all the cars
Panel1.ID = "pnl" + loop.ToString();
Panel1.Style["position"] = "absolute";
Panel1.Style["left"] = "155px";
Panel1.Style["top"] = "400px";
Panel1.Style["Height"] = "200px";
Panel1.Style["Width"] = "1000px";
Panel1.BackColor = System.Drawing.Color.Black;
form1.Controls.Add(Panel1);
if (Add >= 2)
{
int Top = (400 * (Add - 1));
Panel1.Style["top"] = (250 + Top + 20).ToString() + "px"; //Set the second and more panels down
}
Add++;
string Art = s.LoadArt(loop);
string ArtID = Art.Substring(0, Art.IndexOf("|"));
Art = Art.Substring(ArtID.Length + 1);
string ArtName = Art.Substring(0, Art.IndexOf("|"));
Art = Art.Substring(ArtName.Length + 1);
string Description = Art.Substring(0, Art.IndexOf("|"));
Art = Art.Substring(Description.Length + 1);
string PicUrl = Art.Substring(0, Art.IndexOf("|"));
string path = Server.MapPath(PicUrl);
Image image1 = new Image();
image1.ID = "img" + ArtID +loop;
image1.ImageAlign = ImageAlign.AbsMiddle;
image1.Visible = true;
image1.ImageUrl = path;
image1.Style["Left"] = "10px";
image1.Style["position"] = "absolute";
image1.Style["top"] = "10px";
image1.Height = 180;
image1.Width = 230;
Panel1.Controls.Add(image1);
Label label1 = new Label(); //Create a label for the description of each car
label1.ID = "lblDescription" + ArtID;
label1.Text = Description;
label1.ForeColor = System.Drawing.Color.Lime;
label1.BorderStyle = BorderStyle.Groove;
label1.BorderColor = System.Drawing.Color.Violet;
label1.Style["Left"] = "500px";
label1.Style["position"] = "absolute";
label1.Style["top"] = "30px";
Panel1.Controls.Add(label1);
string View = s.TimesView(ArtID);
Label label10 = new Label(); //Create a label for the times each car is viewed
label10.ID = "lblView" + ArtID+loop;
label10.Text = "Times Viewed: " + View;
label10.ForeColor = System.Drawing.Color.Lime;
label10.Style["Left"] = "799px";
label10.Style["position"] = "absolute";
label10.Style["top"] = "170px";
Panel1.Controls.Add(label10);
Button btnView = new Button(); //Create a button to view a car for all cars
btnView.ID = ArtID;
btnView.Text = "View";
btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
btnView.BackColor = System.Drawing.Color.Gray;
btnView.BorderColor = System.Drawing.Color.Violet;
btnView.Style["top"] = "150px";
btnView.Style["left"] = "800px";
btnView.Style["Height"] = "20px";
btnView.Style["position"] = "absolute";
btnView.BorderStyle = BorderStyle.Outset;
btnView.Command += new CommandEventHandler(btnView_Command); //Create a command EventHandler to now what button was clicked
btnView.CommandArgument = ArtID; //Set the commandArguments = to the carID
Panel1.Controls.Add(btnView);
}
}
void btnView_Command(object sender, CommandEventArgs e)
{
string ArtID = e.CommandArgument.ToString(); //Gets theCarId from the CommandArgument
Session["ArtID"] = ArtID; //Create session CarID and set it = to the CarID
Response.Redirect("ViewArt.aspx"); //Redirect to the ViewCar page
}
}